Insertion Sort List

来源:互联网 发布:有名的软件供应商 编辑:程序博客网 时间:2024/06/08 13:37

Sort a linked list using insertion sort.

按照题目要求,这里是从小到大的顺序排列。
解法1:
遍历每一个节点,然后通过一个dummy作为初始的pre节点来判断应该插入在哪里,最后dummy的next就是排序后的第一个节点;

解法2:
这个解法其实就是先从按照从大到小排列,然后反转以下list就行。这个解法更适用在list比较长,而且已经知道几乎是完全有序(从小到大)了得情况下。


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *insertionSortList(ListNode *head) {        ListNode dummy(INT_MIN);        ListNode *cur = head;                // 1        /*        while (cur != NULL) {            ListNode *pre = &dummy;            ListNode *next = cur->next;            while (pre->next != NULL && pre->next->val < cur->val) pre = pre->next;            cur->next = pre->next;            pre->next = cur;            cur = next;        }                return dummy.next;        */                // 2        ListNode *pre = NULL;        while (cur != NULL) {            pre = &dummy;            ListNode *next = cur->next;            while (pre->next != NULL && pre->next->val > cur->val) pre = pre->next;            cur->next = pre->next;            pre->next = cur;            cur = next;        }                pre = NULL;        cur = dummy.next;        while (cur != NULL) {            ListNode *next = cur->next;            cur->next = pre;            pre = cur;            cur = next;        }                return pre;    }};


0 0
原创粉丝点击