【发布时间】:2018-11-04 23:04:36
【问题描述】:
我正在尝试对 C 中的双向链表进行插入排序。在这种状态下,我的代码让我陷入了一个无休止的循环,吐出 8 和 9。
有人可以解释一下“insertionSort”方法应该如何设计吗?
我的链表被设计成包含头、上一个、下一个和一些数据。
这是我目前的代码
我的希望是空的。请帮忙。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
struct Node* previous;
}Node;
struct Node* head = NULL;
struct Node* current = NULL;
struct Node* headsorted = NULL;
int l = 0;
int empty = 1;
int length = 0;
int change = 0;
void InsertSort(){
Node* temp = (Node*)malloc(sizeof(struct Node));
temp = head;
current = head->next;
printf("\nInsert Sort begins...\n");
if (head != NULL && head->next != NULL)
{
for (int i = 1; i < length; i++)
{
while(current->data > current->next->data && current->next != NULL && current != NULL)
{
temp = current;
current = current->next;
current->next = temp;
}
}
}
else
{
printf("\nList Error!\n");
}
temp = NULL;
}
void Insert(int x)
{
Node* temp = (Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = head;
temp->previous = NULL;
if (head != NULL)
{
head->previous = temp;
}
head = temp;
}
void Print(){
struct Node* temp = head;
printf("List is: ");
while(temp != NULL)
{
printf(" %d", temp->data);
temp = temp->next;
}
}
int main()
{
head = NULL;
FILE * file = fopen("List.txt", "r");
fscanf(file, "%d", &l);
while (!feof (file))
{
Insert(l);
fscanf(file, "%d", &l);
length++;
}
fclose(file);
Print();
printf("\n\n\n");
printf("data: %d next: %d " , head->data, head->next->data);
InsertSort();
Print();
return 0;
}
【问题讨论】:
-
temp = head;//???????空?
-
In InsertSort() 也许你需要 head = tmp ?
-
我不这么认为,@purec。看起来
InsertionSort()中的malloc()是一个红鲱鱼。该函数只是泄漏内存。 -
奇怪的是,@TuğberkKaanDuman,
while (!feof (file))的使用是个例外。或者至少,它不匹配总是错误的模式。这是因为文件的第一次读取被提升到循环之前,导致循环条件中的feof()测试实际上是明智的。不过,为了清楚起见,我会将循环内的fscanf()调用移动到循环的最后一条语句。
标签: c doubly-linked-list insertion-sort