C - 如何在删除之前返回值?



我想跳过两个节点,以便访问倒数第二个节点和最后一个节点:

#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。如何从中得到?

查找倒数第二个节点的正确方法,而不会崩溃,并处理列表中少于 2 个节点的情况:

for(;tmp && tmp->next && tmp->next->next;tmp=tmp->next);
if (tmp && tmp->next && tmp->next->next {
// tmp is the penultimate node
} else {
// List does not have at least 2 nodes
}

相关内容

  • 没有找到相关文章

最新更新