【发布时间】:2020-09-30 04:06:10
【问题描述】:
我编写了一个程序来创建和打印单个链表。我使用结构指针指向结构指针来修改列表。当我打印列表时,它只打印添加的最后两个节点。
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node * createnode(int num){
struct node * n;
n=(struct node*)malloc(sizeof(struct node));
n->data=num;
n->next=NULL;
return n;
}
void createlist(struct node **head,int num){
struct node *temp=createnode(num);
*head=temp;
return;
}
void options(){
printf("Enter your choice\n");
printf("1.Add at end\n");
printf("2.Add at beginning\n");
printf("3.Add at location\n");
printf("4.Print list\n");
}
void add_end(struct node **head){
int info;
printf("Value: ");
scanf("%d",&info);
if(*head==NULL){
createlist(head,info);
return;
}
struct node *temp=createnode(info);
struct node **end=head;
while((*end)->next!=NULL){
(*end)=(*end)->next;
}
(*end)->next=temp;
}
void print2(struct node *head){
struct node * temp=head;
printf("\nList :");
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
int main(){
struct node *head=NULL;
createlist(&head,5);
int choice=0;
options();
scanf("%d",&choice);
while(1){
switch(choice){
case 1:add_end(&head);
break;
case 4:print2(head);
break;
default:exit(0);
}
options();
scanf("%d",&choice);
}
return 0;
}
每次,我在列表末尾附加 5 到 6 个节点,当我打印列表时,它只打印最后添加的节点。 不知道是add_end函数还是print函数有问题。
【问题讨论】:
-
如果您只有一个
int作为列表成员,您可以省去create_node()函数,而只需在add()节点函数中完成所有操作。如果你也使用tail指针,你会在列表末尾获得 O(1) 插入。两个例子没有tail指针Singly Linked List (node only, no wrapper),有tail指针Singly Linked List of Integers (example) -
另外,在C语言中,
malloc的返回不需要强制转换,没有必要。见:Do I cast the result of malloc?
标签: c pointers linked-list pointer-to-pointer