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