这是我的插入排序功能:
Student *sort(Student* node)
{
if (node == NULL || !node->next)
return node;
Student *sorted = NULL;
while (node != NULL)
{
Student *head = node;
Student **tail = &sorted;
node = node->next;
while (!(*tail == NULL || head->id < (*tail)->id))
{
tail = &(*tail)->next;
}
head->next = *tail;
*tail = head;
}
return sorted;
}
因此,如果要对3.3,3.1和3.8进行排序,则会对它们进行排序,例如:
3.3 3.8
我不知道第一个元素会发生什么。如果我给它一组更大的文本进行排序,它几乎错过了一半的文本。
一直想弄清楚它为什么会这样做。我很确定这是我的排序功能的问题。
写功能。该函数应该只是将排序后的结果写入文件:
void write(Student* node) {
Student * curr = NULL;
curr = node;
FILE *ptr = fopen("student_out.txt", "w");
if (curr == NULL)
{
printf("Nothing to list. \n");
exit(1);
}
int i=0;
while(curr !=NULL) {
fprintf(ptr,"%d, %s, %s, %s, %.2f\n", curr->id, curr->firstname, curr->lastname, curr->major, curr->gpa);
curr = curr -> next;
}
return;
}
答案 0 :(得分:1)
似乎正在工作,问题可能在于打印输出。用于测试上述情况的示例代码,转换为C89兼容(因为我使用的是Visual Studio)。我会交换名称头部和节点,但我保留它们以匹配原始示例。我还将比较改为停止时(*尾) - &gt; id&gt; head-&gt; id(在比较中使用&lt; =而不是&lt;),以便保留“相等”节点的原始顺序。
#include <stdio.h>
typedef struct Student_{
struct Student_ *next;
double id;
}Student;
Student *sort(Student* node)
{
Student *sorted = NULL;
Student **tail;
Student *head;
if (node == NULL || !node->next)
return node;
while (node != NULL)
{
head = node;
node = node->next;
tail = &sorted;
while (*tail != NULL && (*tail)->id <= head->id)
tail = &(*tail)->next;
head->next = *tail;
*tail = head;
}
return sorted;
}
int main()
{
Student a[3] = {{&a[1],3.3},{&a[2],3.1},{NULL,3.8}};
Student *b;
b = sort(a);
while(b){
printf("%3.1lf ", b->id);
b = b->next;
}
printf("\n");
return 0;
}