您的位置:首页 > 编程语言 > C语言/C++

LeetCode----Insertion Sort List

2015-11-14 17:16 393 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息