【发布时间】:2016-11-03 18:07:00
【问题描述】:
我做了一个排序链表程序。我不知道为什么,但它一次又一次地崩溃。试图修复它,但没有奏效。问题似乎出在 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("%d\n", 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;
}
使用代码块。
【问题讨论】:
-
您应该检查您的
newNode = malloc(...)以确保newNode不为NULL。此外,curr未初始化,因此while(curr != 0)是未定义的行为。curr->val肯定是段错误。 -
while(curr != 0)和if(curr->val >= newNode->val)在分配给curr之前使用。您的程序有未定义的行为。 -
我应该用什么初始化,curr?使这个程序工作。
-
head。要遍历一个链表,从head开始并迭代直到你到达NULL -
我确实这样做了,但仍然崩溃
标签: c linked-list