【发布时间】:2012-02-10 15:27:43
【问题描述】:
我正在完成一项大学作业。我正在尝试用 C 编写一个链表排序。我不允许交换值 - 只能交换指针。
这是我的排序功能:
struct node *sort_list(struct node *head) {
bool swapped ;
struct node *cur = head, *first ;
if ( head == NULL || head->next == NULL ) return head ;
else {
do {
swapped = false ;
while ( cur != NULL && cur->next != NULL ){
if (cur->value > cur->next->value){
cur = swap_with_next( cur ) ;
swapped = true ;
}
cur = cur->next ;
}
} while (swapped == true) ;
}
return head ;
}
还有交换功能:
struct node *swap_with_next(struct node *n) {
struct node *tmp ;
tmp = n ;
n = n->next ;
tmp->next = n->next ;
n->next = tmp ;
return n ;
}
问题:输出不正确:
input: 5->2->NULL
output: 5->NULL
input: 9->1->5->2->8->3
output: 9->5->8
任何帮助将不胜感激!
【问题讨论】:
-
投票结束:使用调试器可以解决(或至少确定)问题。
-
swap_with_next更新n和n->next中的指针,但不更新继续指向n 的前一个节点,即使它不再是下一个元素。
标签: c pointers data-structures linked-list