LeetCode: Insertion Sort List
Sort a linked list using insertion sort.
地址:https://oj.leetcode.com/problems/insertion-sort-list/
算法:按题目的意思,采用插入排序对链表进行排序,时间复杂度为$O(n^2)$。代码:
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 ListNode *insertionSortList(ListNode *head) {
12 ListNode *p = head, *q = NULL, *pre = NULL;
13 if(p){
14 p = p->next;
15 head->next = NULL;
16 }
17 while(p){
18 pre = NULL;
19 q = head;
20 while(q && q->val <= p->val){
21 pre = q;
22 q = q->next;
23 }
24 if(pre){
25 pre->next = p;
26 p = p->next;
27 pre->next->next = q;
28 }else{
29 head = p;
30 p = p->next;
31 head->next = q;
32 }
33 }
34 return head;
35 }
36 };