我正在尝试使用选择排序对链接列表进行排序。我只能操作链表指针而不能更改键。我想我有功能逻辑,但是我只返回原始的未排序序列。
bool nodeSwap(Node* head){
Node* next = head->next;
if(next == NULL){ return head;}
head->next = next->next;
next->next = head;
head = next;
return next;
}
Node* sort_list(Node* head){
for(Node* n = head; n->next != NULL; n = n->next){
for(Node* n1 = head->next; n1 != NULL; n1 = n1->next){
if(n-> key > n1->key){
nodeSwap(n);
}
}
}
return head;
}
编辑
好的,所以我经历并添加了更多和一些逻辑,这一次实际上是有意义的,我的功能几乎可以工作......唯一的问题是它总是跳过对列表中前两个元素的排序并且不返回排序后。关于为什么会发生这种情况的任何想法?
Node* sort_list(Node* head){
Node* curr;
Node* prev;
for(curr = head; curr->next != NULL; curr = curr->next){
if(curr == head){
head = curr->next;
curr->next = head->next;
head->next = curr;
prev = head;
}
else if(curr->key > curr->next->key){
head = curr->next;
curr->next = head->next;
head->next = curr;
prev = head;
} else if(curr -> next -> next != NULL){
prev->next = curr->next;
curr->next = prev->next->next;
prev->next->next = curr;
}else if(head != curr){
prev = prev->next;
}else{}
}
return head;
}