【发布时间】:2017-10-19 22:35:43
【问题描述】:
我正在尝试在链表中编写一些基本函数,其中一个是排序插入。我明白它应该做什么,但它给了我一个半排序的列表。我不知道问题出在哪里。它可以完成工作,但有些数字不在正确的位置。因此,如果您能找到发生这种情况的确切位置,我将不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct node {
int data;
struct node* next;
};
struct node* sorted_insert(struct node* ptr, int data){
struct node* newNode = malloc(sizeof(struct node));
if (!newNode){
printf("something went wrong using malloc");
}
newNode -> data = data;
if(ptr->next == NULL) {
newNode -> next = ptr; //ptr is the most recent element
return newNode;
} else {
struct node* prev = ptr->next;
struct node* current = ptr;
if(prev->next == NULL){
if((current -> data) < (newNode -> data)){
newNode -> next = ptr;
return newNode;
} else {
newNode -> next = ptr->next;
ptr -> next = newNode;
return ptr;
}
} else {
while((current -> data) > data && (prev -> data) > data) {
current = prev;
prev = prev->next;
}
newNode -> next = prev;
current -> next = newNode;
return ptr;
}
}
}
struct node* insert(struct node* ptr, int data){
struct node* newNode = malloc(sizeof(struct node));
if (!newNode){
printf("something went wrong using malloc");
}
newNode -> data = data;
newNode -> next = ptr;
return newNode;
}
void print(struct node* root){
struct node* trav = root;
while(trav->next != NULL){
printf("%d\n", trav -> data);
trav = trav -> next;
}
}
int main(){
struct node *head = NULL;
head = malloc(sizeof(struct node));
if (!head){
printf("something went wrong using malloc");
}
head -> data = -1;
head -> next = NULL;
int i;
srand(time(NULL));
for(i = 0; i < 20; i++) {
head = sorted_insert(head, rand()%2000);
print(head);
printf("\n");
}
//printf("number of elements %d\n", length(head));
//print(head);
}
见sorted_insert函数
样本输出:
1279
1755
1295
1983
1353
1313
1924
1635
1296
1807
1263
1257
1199
771
386
359
278
231
141
45
【问题讨论】:
-
正如@klutt 所说。拆分问题,然后单独调试每个部分。测试 find_place() ,每端都有值,最后,比结尾少一个,在中间某处。使用一个空列表进行测试,一个具有一个值的列表,一个具有两个值的三个。在 find_place() 通过这些测试之前,不要尝试插入任何东西。通过 DEBUGGING 让它通过,使用你的调试器,或者至少使用许多额外的 printf 语句来检查正在发生的事情,从而修复一些东西并使测试通过。这就是软件开发的本质:编写代码(容易)、测试(不容易)和调试(困难)。冲洗/重复。
-
修正像this
标签: c linked-list