我正在为我的一个类写一个程序,我卡在询问的部分按升序对链表进行排序。我试着整理列表,但是什么时候我运行这个函数,它只输出第一个值。我知道打印函数是有效的因为我可以在没有插入排序的情况下运行它,并且它打印得很好。
我的代码如下:#include "linkedList.h"
#include <stdlib.h>
#include <stdio.h>
void swap(struct Link *first, struct Link *second){
struct Link* temp = first;
temp->next = first->next;
temp->value = first->value;
first = second;
first->next = second->next;
first->value = second->value;
second = temp;
second->next = temp->next;
second->value = temp->value;
}
struct Link* listInsertionSort(struct Link* head) {
/*
* This function should perform an insertion sort on the list whose head is
* provided as the function's argument, so that the values in the list are
* sorted in ascending order, starting at the head.
*
* The sort should be done without allocating any new Link structs or any
* other auxiliary data structures.
*
* Return a pointer to the new head of the list.
*/
struct Link* cur = head;
cur->next = head->next;
struct Link* count;
for(;cur->next != NULL; cur = cur->next){
for(count = cur->next; count != NULL; count = count->next){
if(cur->value < count->value){
swap(cur, count);
}
}
}
return cur;
}
和linkedList.h文件在这里:
#ifndef __LINKEDLIST_H
#define __LINKEDLIST_H
#define TYPE int
/* Single link structure */
struct Link {
TYPE value;
struct Link* next;
};
struct Link* listInsertionSort(struct Link* head);
struct Link* reverseList(struct Link* head);
struct Link* reverseListRecursive(struct Link* head);
#endif
测试文件在这里(虽然这里不应该有任何错误)因为这是由我们的老师提供给班上所有学生的):
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <float.h>
#include "linkedList.h"
struct Link* buildLink(int n, int rev, int mod) {
struct Link* head = (struct Link*)malloc(sizeof(struct Link));
struct Link* cur = head;
for (int i = 0; i < n; i++) {
if (rev)
cur->value = n - i - 1; //If rev is 1, creates list from high value to low value
else
cur->value = i; //If rev is 0, creates list from low value to high value
if (mod)
cur->value = cur->value % mod; //Modifies list so that it increments up to value of mod
if (i + 1 < n)
cur->next = (struct Link*)malloc(sizeof(struct Link)); //Creates next link in the array
else
cur->next = 0; //If less than the cap it sets next character to NULL, ending the list
cur = cur->next; //Sets current link to next link to continue for loop
}
return head;
}
void printLL(struct Link* l,char* s) {
printf("LL %s: ",s);
while (l != 0) {
printf("%d ", l->value);
l = l->next;
}
printf("n");
}
int main() {
// We aren't practicing good memory management
// here....
struct Link* l = buildLink(10, 0, 4);
struct Link* r = listInsertionSort(l);
printLL(r, "Sort 0-9 mod 4"); //This should print 0 0 0 1 1 1 2 2 3 3
}
有人知道这里的问题是什么吗?错误是在listInsertionSort某处(结构链接*头),但我已经尝试了多种不同的组合,没有成功。
当前输出为:LL Sort 0-9 mod 4: 1当应该是:LL Sort 0-9 mod 4: 0 0 0 1 1 1 2 2 3 3
我找到了解决问题的方法。
不是返回cur,而是返回head。我还更改了swap函数,使其不包括列表中链接的交换值,因为这是不必要的,看起来很乱。