【发布时间】:2018-08-04 01:20:35
【问题描述】:
我无法理解这段代码如何对链表进行排序。
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循环比较两个节点point和small。如果需要切换数据,则下一个代码块实际进行切换,然后stay 移动到列表中的下一个节点,point 是之后的节点。代码如何知道回到第一个节点并继续比较,以便 2 与 1 切换?感谢您的帮助。
【问题讨论】:
-
我可能是错的,但这看起来像selection sort。
-
@tonysdg 你不是,它是...
标签: c sorting linked-list