经过近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
节点中包含当前值。如果接下来是null
,那么列表结束并且列表中的数字是最高的,因此它将被插入到最后的位置,如果该数字是中间的某个位置,则prev节点的地址部分被存储在临时节点中地址部分现在临时节点指针保存下一个节点的地址。
编辑:我的代码问题是如果我输入1,2我得到错误信息为a.exe has stopped working
。我正在使用MinGW进行编译。我打破了循环时,用户输入0
''\ 0''与NULL不相同。 http://stackoverflow.com/questions/1296843/what-is-the-difference-between-null-0-and-0 – mohit
@mohit,''\ 0''将和'NULL'完全一样。它在语义上并不真正有意义,但它应该没问题。 –