c - 如何从队列中删除集合节点

标签 c queue

我希望从队列中删除一个集合节点。假设我按名称 I.D 搜索选择节点。我知道如何从队列前面删除某些内容,但对如何在用户设置点(例如中途)删除某些内容感到困惑。

我的功能:

void retrieveAndRemove(linkedPtr*hd, int size){
linkedPtr temp = *hd;


   if (hd == NULL){
    printf("List is empty!");

   }
    while( temp != NULL){
        if (temp->status == IN_RESTAURANT && temp->size == size){

            //HERE is where I am stuck, how do i now re-arrange the que
            //Such that the node gets removed and the next node is linked
            free(temp);
            return;

        }
        temp = temp->next;
    }

}

最佳答案

当您需要从链表中间删除一个节点时,您需要跟踪前一个节点。这将允许您重置链接列表中的链接。

起始状态:

                         Node to be removed
                            |
                            v
+-------+                +-------+             +-------+
| node1 |  -- next -->   | node2 | -- next --> | node3 |
+-------+                +-------+             +-------+

结束状态:

+-------+                                      +-------+
| node1 |                -- next -->           | node3 |
+-------+                                      +-------+

这是您的函数的修订版本,应该可以工作。

// This wont work for the case when the head needs to be removed.
// void retrieveAndRemove(linkedPtr*hd, int size) {

void retrieveAndRemove(linkedPtr** hd, int size) {

   linkedPtr prev = **hd;
   linkedPtr cur = prev;

   if (hd == NULL){
      printf("List is empty!");
      return;
   }

   // Take care of the case where the item to be removed is at the head.
   if ( cur->status == IN_RESTAURANT && cur->size == size) {
      *hd = cur->next;
      free(cur);
   }

   // Take care of the case where the item to be removed is in the middle.
   while( cur != NULL) {
      if (cur->status == IN_RESTAURANT && cur->size == size){

         // Fix the links.
         prev->next = cur->next;
         free(cur);
         return;
      }
      prev = cur;
      cur = cur->next;
   }
}

关于c - 如何从队列中删除集合节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33220637/

相关文章:

c、正确使用线程

java - 按元音数量对 ArrayList 中的字符串进行排序

c - 我想知道 c while 谓词中发生了什么?

c++ - RTOS 中第一个任务切换的代码

c - 从文件中读取值 - 有些是正确的,有些是不正确的

java - 对对象数组列表进行排序问题

python - Python 中的链接工作池

字符对齐奇怪的输出

java - 在 Java 8 中耗尽队列的惯用方法是什么?

javascript - 在 jquery 中编写一个全局动画队列