【发布时间】:2020-09-18 10:22:16
【问题描述】:
我想跳过两个节点,以便访问倒数第二个节点和最后一个节点:
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
typedef struct node node_t;
//prototypes
node_t *create(int);
node_t *push(node_t *, node_t **);
node_t *shift(node_t *);
int main(void){
node_t *h = 0;
for(int i =0; i<23 ; i++)
push(create(i+1),&h);
shift(h);
}
node_t *create(int value){
node_t *new = malloc(sizeof(node_t));
new->value=value;
//new->next=0;
return new;
}
node_t *push(node_t *new, node_t **head){
new->next = *head;
*head=new;
return new;
}
node_t *shift(node_t *head){
node_t *tmp = head; //do not change head pointer
for(;tmp;tmp=tmp->next->next); //jump over 2 nodes, to have access to last node and penultimate
node_t *last = tmp->next; //one before null node (the very last), the one I want return;
tmp->next = 0; //now delete it, so last node will become penultimate one
return last;
}
但这会给 - command terminated。我知道我正在返回 null,但是在删除节点之前如何返回?因为 return 是要执行的最后一个命令,所以它必须是最后一个。但后来我返回 0。如何从中得到?
【问题讨论】:
-
@autistic456 目前尚不清楚您要对列表做什么。
-
@VladfromMoscow,
shift-> 与push相反:删除最后一个元素/节点并返回它。它与 perl shift 中的逻辑相同 -
@autistic456 更符合逻辑的是删除第一个节点,因为您有一个支持 FIFO 模型的单链表。
-
一次跳过两个列表不是找到倒数第二个节点的正确方法。一次浏览列表中的一项。要么在前面两个链接为空时停止,要么在到达末尾时停止,但包含用于记住最新项目的代码。请务必处理列表少于两个项目的情况。
-
直到
tmp为NULL,您的循环才会停止,然后在下一行使用tmp->next取消引用它。繁荣。
标签: c data-structures linked-list