LeetCode----Insertion Sort List

Insertion Sort List

Sort a linked list using insertion sort.


分析:

使用插入排序对链表进行排序。

可以新建一个带头节点的有序链表,每次从原链表中选择一个节点,插入到带头节点的链表中。


C++代码:

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode dummy = ListNode(-1);
        ListNode * cur = head, *p, *pnext, *t;
        while(cur){
            p = &dummy;
            while(p->next && cur->val > p->next->val){
                p = p->next;
            }
            pnext = p->next;
            p->next = cur;
            t = cur->next;
            cur->next = pnext;
            cur = t;
        }
        return dummy.next;
    }
};


Python的代码不知道为什么一直TLE。

先贴上,等回头再过来改。

class Solution(object):
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        cur = head
        # dummy是新的链表表头
        dummy = ListNode(-1)
        while cur:
            p = dummy
            while p.next and cur.val > p.next.val:
                p = p.next
            pNext = p.next
            p.next = cur
            t = cur.next
            cur.next = pNext
            cur = t
        return dummy.next

你可能感兴趣的:(LeetCode,C++,python,插入排序)