我想创建一个排序链接列表,因此每次插入一个元素时,都应该按照升序排序。现在我做了一个排序的链接列表。该方案工作正常,但有一个问题。它不会在已排序的链接列表中打印中间和最后一个插入的元素,即使它已插入。程序不打印我需要打印的内容
我的代码是这一计划的
//Libraries
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct Node{
int val;
struct Node *next;
};
struct LLADT{
struct Node *head;
};
// Initializing Linked List
void init(struct LLADT *LL){
LL->head = 0;
}
// Sorted Inserted Linked List Function
void sortInsert(struct LLADT *LL, int num){
struct Node *temp;
struct Node *temp2;
temp = (struct Node*)malloc(sizeof(struct Node));
// If list is Empty
if(LL->head == 0){
temp-> val = num;
temp->next = NULL;
LL->head = temp;
return;
}
// When list is not empty and key is smallest
if(num < LL->head->val){
temp-> val = num;
temp->next = LL->head;
LL->head = temp;
return;
}
// When list is not empty and we have to insert in middle
temp2 = LL->head;
temp-> val = num;
temp->next = NULL;
while(temp2->next !=0){
if(num > temp2->next->val){
temp2 = temp2->next;
}
else{
temp2->next = temp->next;
temp->next = temp2;
return;
}
}
// When list is not empty and we have to insert at the end
if(num > temp->val){
temp->val = num;
temp->next = NULL;
temp2->next = temp;
return;
}
}
//Printing Linked List
void print_list(struct LLADT *LL){
struct Node *temp;
temp = LL-> head;
while(temp !=0){
printf("%d\n", temp->val);
temp = temp -> next;
}
}
// Main Function
int main(){
struct LLADT LL;
init(&LL);
// inserting
sortInsert(&LL,17);
sortInsert(&LL,3);
sortInsert(&LL,5);
sortInsert(&LL,2);
sortInsert(&LL,1);
sortInsert(&LL,20);
//Printing
print_list(&LL);
getch();
return 0;
}
输出是:
1
2
3
,我使用的Visual Studio 2012旗舰版。
而_你正需要它来打印吗?请以文本形式显示预期和实际输出,而不是图像。 –
“插入到中间”块中的逻辑似乎已中断。这当然令人困惑。访问'temp2-> next-> val'看起来像在接近列表末尾时可以取消引用'NULL'... – unwind
了解如何使用调试器的时间。 –