思路:新建一个链表头,遍历原链表,将每个节点加入新链表正确的位置。每一次寻找正确的新位置时,都需要从已排序新链表头结点开始遍历比较。
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* insertionSortList(ListNode* head) {
//哑节点
ListNode *dumy = new ListNode(0);
ListNode *cur = head;
ListNode *pre = dumy;
while (cur != nullptr) {
//保存当前节点下一个节点
ListNode* next = cur->next;
pre = dumy;
//寻找当前节点正确位置的一个节点
while (pre->next != nullptr && pre->next->val < cur->val) {
pre = pre->next;
}
//将当前节点加入新链表中,注意已排序节点的最会一个节点指向nullptr节点。
cur->next = pre->next;
pre->next = cur;
//处理下一个节点
cur = next;
}
return dumy->next;
}
int main() {
int n;
cin >> n;
ListNode *head = new ListNode(0);
ListNode *curr = head;
for (int i = 0; i < n; i++) { //创建单链表
int a;
cin >> a;
ListNode *temp = new ListNode(a);
curr->next = temp;
curr = temp;
}
head = insertionSortList(head->next);
while (head != nullptr) {
cout << head->val << " ";
head = head->next;
}
return 0;
}