我做了一个排序链表程序。我不知道为什么,但它一次又一次地崩溃。试图解决它,但没有工作。问题似乎是在print_list函数,但不知道是什么问题。这是我的代码。
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct node{
struct node *next;
int val;
};
struct LLADT{
struct node *head;
};
void init(struct LLADT *LL){
LL-> head = 0;
}
// Printing a linked list
void print_list(struct LLADT *LL){
struct node *temp;
temp = LL-> head;
while(temp ->next!=NULL){ // changed temp!=NULL to temp->next!=NULL
printf("%dn", temp->val);
temp = temp -> next;
}
}
//inserting sorted elements
void sortInsert(struct LLADT *LL, int num){
struct node *newNode;
newNode->val = num;
newNode->next = 0;
newNode =(struct node*)malloc(sizeof(struct node));
// Case -1: List is empty
if(LL->head == 0){
LL->head = newNode;
}
else{
struct node *curr;
curr = LL->head;
struct node *prev;
prev = NULL;
// Traversing list to find the insert location
while(curr != 0){
if(curr->val >= newNode->val){
break;
}
else{
prev = curr;
curr = curr -> next;
}
// Case-2:
if(curr == LL->head){
newNode->next = LL->head;
LL->head = newNode;
}
// case-3
else{
newNode->next = curr;
prev->next = newNode;
}
}
}
}
int main(){
struct LLADT LL;
sortInsert(&LL,17);
sortInsert(&LL,3);
sortInsert(&LL,5);
sortInsert(&LL,2);
sortInsert(&LL,1);
sortInsert(&LL,20);
//print_list(&LL);
getch();
return 0;
}
使用codeblocks 。
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct node{
struct node *next;
int val;
};
/*struct LLADT{
struct node *head;
};*/
struct node * head ;
void init(){
head = NULL;
}
// Printing a linked list
void print_list(){
struct node *temp;
temp = head;
while(temp !=NULL){
printf("%dn", temp->val);
temp = temp -> next;
}
}
//inserting sorted elements
void sortInsert(int num){
struct node *newNode;
struct node *curr;
newNode =(struct node*)malloc(sizeof(struct node));
newNode->val = num;
newNode->next = NULL;
// Case -1: List is empty
if(head == NULL){
head = newNode;
}
else{
curr=head;
while(curr->next!=NULL){
curr=curr->next;
}
curr->next=newNode;
// Traversing list to find the insert location
// while(curr != NULL){
// if(curr->val >= newNode->val){
// break;
// }
// else{
// prev = curr;
// curr = curr -> next;
// }
// Case-2:
// if(curr == LL->head){
// newNode->next = LL->head;
// LL->head = newNode;
//}
// case-3
//else{
// newNode->next = curr;
// prev->next = newNode;
// }
//}
}
}
int main(){
//struct LLADT LL;
sortInsert(17);
sortInsert(3);
sortInsert(5);
sortInsert(2);
sortInsert(1);
sortInsert(20);
print_list(head);
getch();
return 0;
}
您可以尝试这段代码,因为不需要为head
声明其他struct
。注释掉不需要的代码