【发布时间】:2020-09-18 09:25:49
【问题描述】:
将近 3 年后,我开始重新学习 C。
我创建了一个Linked list,并希望将其扩展到创建一个排序的链表。这是我的代码:
typedef struct node{
int data;
struct node *ptr;
}node;
node* insert(node* head, int num){
node *temp,*prev,*next;
temp = (node*)malloc(sizeof(node));
temp->data = num;
temp->ptr = '\0';
if(head=='\0'){
head=temp;
}else{
next = head;
prev = next;
while(next->data<=num){
prev = next;
next = next->ptr;
}
if(next==NULL){
prev->ptr = temp;
}else{
temp->ptr = prev->ptr;
prev-> ptr = temp;
}
}
return head;
}
void main(){
int num;
node *head, *p;
head = '\0';
do{
printf("Enter a number");
scanf("%d",&num);
if(num!=0)
head = insert(head,num);
}while(num!=0);
p = head;
printf("\nThe numbers are:\n");
while(p!='\0'){
printf("%d ",p->data);
p = p->ptr;
}
}
这是我的想法。我遍历列表,直到找到输入的数字>=。我将前一个节点存储在prev 中,next 节点包含当前值。如果next是null,则列表结束,列表中编号最高的,所以要插入最后一个位置,如果编号在中间某个位置,则prev节点的地址部分存储在临时节点地址部分现在临时节点指针保存下一个节点的地址。
编辑: 我的代码有问题,如果我输入 1,2,我会收到 a.exe has stopped working 的错误消息。我正在使用 MinGW 进行编译。当用户输入 0 时,我正在打破循环。
【问题讨论】:
-
'\0'与 NULL 不同。 stackoverflow.com/questions/1296843/… -
@mohit,
'\0'的工作方式与NULL完全相同。它在语义上并不真正有意义,但应该没问题。
标签: c linked-list