【问题标题】:Searching for an item linked list C (queue)搜索项目链表C(队列)
【发布时间】:2013-02-27 22:30:09
【问题描述】:

我有两个结构名称 *head 和 *tail。

我使用 head 作为链表的开始,使用 tail 作为结束。

假设我有一个包含任意数量元素的链表

typedef struct queue
{
    int stuff;
    struct queue *nextNode;
}q;

在我的一个节点中,stuff = 164(这是假设的)

我将如何搜索我的链接列表以找到 164?

谢谢!

【问题讨论】:

  • 迭代:检查第一个。如果是164,你就完成了。否则检查下一个节点(除非为 NULL)。

标签: c linked-list queue traversal


【解决方案1】:

获取指向链表头部的指针。假设列表中的最后一项标记为nextNode,其指针为NULL,则可以逐个遍历列表:

struct queue *tmp = head;
while (tmp != NULL) {
    if (tmp->stuff == 164) {
        // found it!
        break;
    }
    tmp = tmp->nextNode;
}

【讨论】:

  • 非常感谢。很有道理!
【解决方案2】:
struct queue *find(struct queue *ptr, int val) {
 for ( ; ptr; ptr = ptr->nextNode) {
     if (ptr->stuff == val) break;
     }
 return ptr;
}

【讨论】:

    【解决方案3】:

    只需遍历您的队列

    struct queue *current = head;
    
    while(current != NULL)
    {
        if(current->stuff == numToSearch)
            // found it
        current = current->nextNode;
    
    }
    

    注意:请原谅任何轻微的语法错误,我已经有一段时间没有接触 c 了

    【讨论】:

      【解决方案4】:

      从头开始。虽然未达到尾部且当前项目值不是我们要寻找的值,但转到下一个节点。如果项目完成,则循环不是我们正在寻找的 -> 列表中不存在这样的项目。代码是在尾指针不为 NULL 的假设下编写的。

      struct queue* item = head;
      while (item != tail && item->stuff != 164) {
          item = item->nextNode;
      }
      if (164 == item->stuff) {
      // do the found thing
      } else {
      // do the not found thing
      }
      

      【讨论】:

        猜你喜欢
        • 2016-04-06
        • 1970-01-01
        • 2019-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多