我有一些代码来合并、排序一个包含字符串作为数据值的链表。我的目标是按字母顺序对链表中的节点进行排序。
下面是我定义节点的方式:
struct Node {
void *data;
struct Node* next;
}; 这就是我在main中对列表进行排序的调用:
int main()
{
struct Node* a = NULL;
struct Node* sorted = NULL;
push(&a, "orange");
push(&a, "banana");
push(&a, "strawberry");
push(&a, "apple");
push(&a, "kiwi");
push(&a, "grapes");
sorted = MergeSort(a);
printf("Sorted Linked List is: \n");
printList(sorted);
return 0;
} push函数将一个元素插入到链表的开头,而printList函数将打印列表中的每个元素,后面跟着一个换行符。
我可以确认push和printList函数工作正常,因为当我测试它时,列表a的所有元素都被打印出来了。
下面是我用来按字母顺序排序列表的代码:
/* sorts the linked list by changing next pointers (not data) */
struct Node* MergeSort(struct Node* headRef)
{
struct Node* head = headRef;
struct Node* a;
struct Node* b;
/* Base case -- length 0 or 1 */
if ((head == NULL) || (head->next == NULL)) {
return headRef;
}
/* Split head into 'a' and 'b' sublists */
FrontBackSplit(head, &a, &b);
/* Recursively sort the sublists */
MergeSort(a);
MergeSort(b);
/* answer = merge the two sorted lists together */
headRef = SortedMerge(a, b);
return headRef;
}
struct Node* SortedMerge(struct Node* a, struct Node* b)
{
struct Node* result = NULL;
/* Base cases */
if (a == NULL)
return (b);
else if (b == NULL)
return (a);
/* Pick either a or b, and recur */
if (strcmp(a->data, b->data) <= 0) {
result = a;
result->next = SortedMerge(a->next, b);
}
else {
result = b;
result->next = SortedMerge(a, b->next);
}
return (result);
}
/* UTILITY FUNCTIONS */
/* Split the nodes of the given list into front and back halves,
and return the two lists using the reference parameters.
If the length is odd, the extra node should go in the front list.
Uses the fast/slow pointer strategy. */
void FrontBackSplit(struct Node* source,
struct Node** frontRef, struct Node** backRef)
{
struct Node* fast;
struct Node* slow;
slow = source;
fast = source->next;
/* Advance 'fast' two nodes, and advance 'slow' one node */
while (fast != NULL) {
fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
/* 'slow' is before the midpoint in the list, so split it in two
at that point. */
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
} 当我在排序过程之后打印列表sorted时,我的输出如下所示:
Sorted Linked List is:
grapes
kiwi
strawberry这表明排序工作正常,但是并不是所有的元素都被输出。我想知道为什么会出现这种情况?
发布于 2019-10-20 01:51:20
/* Recursively sort the sublists */
MergeSort(a);
MergeSort(b); 这就是问题所在。您正在对子列表进行排序,但是在对它们进行排序之后,您并没有更新a和b以指向列表中相应的新头部。
更改为
/* Recursively sort the sublists */
a = MergeSort(a);
b = MergeSort(b); 并且它的行为符合预期。
https://stackoverflow.com/questions/58466127
复制相似问题