了解链表排序

时间:2018-08-04 01:20:35

标签: c sorting linked-list

我很难理解这段代码如何对链表进行排序。

node* sort(node *head) {
    struct node* point;
    struct node* small;
    struct node* stay;
    int temp;
    stay = head;

    while (stay != NULL) {
        point = stay->next;
        small = stay;
        while (point != NULL) {
            if (point->data < small->data) {
                small = point;
            }
            point = point->next;
        }
        temp = stay->data;
        stay->data = small->data;
        small->data = temp;
        stay = stay->next;
    }
    return head;
}

我尝试在纸上进行跟踪,并且我的思考过程使我相信,如果我们要运行此功能,则列表的排序如下:

5 -> 2 -> 1 -> 3  
2 -> 5 -> 1 -> 3  
2 -> 1 -> 5 -> 3  
2 -> 1 -> 3 -> 5  

我的理解是,第一个while循环每次都会遍历列表,直到到达最后一个节点,而第二个while循环比较两个节点pointsmall。如果需要交换数据,则实际上是下一个代码块进行了交换,然后stay移至列表中的下一个节点,其中point是其后的节点。代码如何知道要回到第一个节点并进行比较,以使2与1切换?谢谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这段代码实现了选择排序:从staysmall == stay)开始,它搜索紧随其后的最小值,并在找到后立即查找(即列表的末尾)达成)。

请注意,在stay最小的情况下,它会与自身交换(您可以在if(small != stay) { /* swap */ }之前通过适当的测试来防止这种情况的发生。

实际上,您的排序步骤如下:

5 -> 2 -> 1 -> 3
1 -> 2 -> 5 -> 3
1 -> 2 -> 5 -> 3 (second node swapped with itself)
1 -> 2 -> 3 -> 5
1 -> 2 -> 3 -> 5 (fourth node swapped with itself)

实际上,还有一步,因为最后一个节点总是与自身交换(while(stay != NULL)仅在最后一个节点之后停止)。

因为stay最初设置为head,所以从开始(在外部循环的第一次运行)开始就正确地对待了第一个节点。