如何在链表末尾添加元素?
这是我的尝试,但我知道有一些不正确的事情:
typedef struct node_struct{
int data;
struct node_struct *next;
}node;
node *end(node *p){
node *new = malloc(sizeof(node));
node *next;
int value;
printf("Insert new element: ");
scanf("%d",&value);
p->next = next;
new->data = value;
next = new->data;
return next;
return next;
}
现在这是我的代码,但它仍然不起作用:
node *end(node *p){
node *new = malloc(sizeof(node));
node *next;
int value;
printf("Insert new element: ");
scanf("%d",&value);
p->next = next;
new->data = value;
while(next->next){
next = next->next;
}
next->next = new;
return new;
}
在添加新节点之前,首先需要迭代到链表的末尾。
node *end(node *p){
// ...
node *next = p;
while(next->next){
next = next->next;
}
...
next->next = new;
return new; // Returns end of the linked list
}
请注意,您通常应该检查p
是否为null,如果为null,则返回错误代码,或者以其他方式处理错误。
问题解决了,这段代码运行良好,至少我认为是这样
void end(node *head){
node *new = malloc(sizeof(node));
node *next;
int value;
next = head->next;
printf("Insert number to add at the end: ");
scanf("%d",&value);
new->data= value;
while(next->next){
next = next->next;
}
next->next = new;
}