c - 如何在链表中跟踪我的尾节点

标签 c list

如何跟踪我的尾节点以便快速返回它的值。到目前为止,这就是我创建列表的方式,但我想编写一个可以返回最后一个节点并将其从列表中删除的函数。不太确定从哪里开始

typedef struct node_t{
    int val;
    struct node_t *next;
}node_t;

int main(int argc, char *argv[])
{
    int input;
    node_t *list;
    list = NULL;
    list = push(1,list);
    list = push(2,list);
    list = push(3,list);
    return 0;
}


node_t *push(int input, node_t *list)
{
    if(list == NULL)
    {
        list = makeStack(input, list);
        return list;
    }

    else
    {
        list->next = push(input,list->next);
    }
    return list;
}

最佳答案

基本上有两种方法:

您可以使用如下函数计算最后一个节点的指针:

node_t * find_last( node_t * ptr )
{
 /* is this node last? */
 if ( ptr->next == NULL )
  return ptr;

 /* let's travel to last node */
 do
  ptr = ptr->next;
 while ( ptr->next != NULL );

 /* and then return it */
 return ptr;
}

但是对于大列表,此功能可能很昂贵。

第二种方法要求您简单地将最后一个指针的值缓存在某种“基本”结构中。

typedef struct
{
 node_t * first;
 node_t * last;
} linked_list_t;

关于c - 如何在链表中跟踪我的尾节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540076/

相关文章:

java - 如何替换 RDD 的元素

javascript - 将 HashString 从 C 转换为 JS

char* 到 float*

c - 如何通过将数字添加到数组 'name' (即存储第一个元素地址的常量指针)来访问数组的元素?

c# - 如何使用 EF 从列表中检查不添加重复项

c# - 查找 C# 列表中重复项的计数

c - C 中的线程间通信

c++ - 传递给 C 库的函数指针的 C 链接

vba - 以编程方式从 Excel 下拉列表中选择

python - 来自两个列表的数字对