Sort a linked list using insertion sort.
// Type your C++ code and click the "Run Code" button!
// Your code output will be shown on the left.
// Click on the "Show input" button to enter input data to be read (from stdin).
#include
using namespace std;
#include
#include
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (head == NULL) {
return NULL;
}
ListNode *cur = head->next; //第一个点已经排好序
ListNode *result_head = head; //结尾链表的头结点,每次遍历的开始
ListNode *prev = head;
while (cur) {
ListNode *next = cur->next;
//优化,如果cur大于prev,那么直接进入下一个节点
if (cur->val >= prev->val) {
prev = cur;
cur = next;
continue;
}
//找到一个比cur大的节点
ListNode *tmp_cur = result_head;
ListNode *tmp_prev = NULL;
while (tmp_cur->val < cur->val) {
tmp_prev = tmp_cur;
tmp_cur = tmp_cur->next;
}
if (tmp_cur == cur) { //到达当前节点,不必排序,只更新prev节点即可
prev = cur;
}
else {
//断开当前节点
prev->next = next;
if (tmp_prev == NULL) {
//插入到开始
cur->next = result_head;
result_head = cur;
}
else { //插入到tmp_prev的后面
cur->next = tmp_prev->next;
tmp_prev->next = cur;
}
}
cur = next;
}
return result_head;
}
};
int main() {
Solution so;
ListNode ln(10), ln1(2), ln2(-1), ln3(9), ln4(4);
ln.next = &ln1;
ln1.next = &ln2;
ln2.next = &ln3;
ln3.next = &ln4;
ListNode *result = so.insertionSortList(&ln);
while (result) {
cout << result->val << " ";
result = result->next;
}
return 0;
}