LeetCode-Insertion Sort List (Python)
2014-06-27 19:42
483 查看
【问题】
Sort a linked list using insertion sort.
【代码】
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if head == None or head.next == None:
return head
dummy = ListNode(0)
dummy.next = head
cur = head
while cur.next != None:
if cur.next.val < cur.val:
pre = dummy
while pre.next.val < cur.next.val:
pre = pre.next
temp = cur.next
cur.next = temp.next
temp.next = pre.next
pre.next = temp
else:
cur = cur.next
return dummy.next
Sort a linked list using insertion sort.
【代码】
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if head == None or head.next == None:
return head
dummy = ListNode(0)
dummy.next = head
cur = head
while cur.next != None:
if cur.next.val < cur.val:
pre = dummy
while pre.next.val < cur.next.val:
pre = pre.next
temp = cur.next
cur.next = temp.next
temp.next = pre.next
pre.next = temp
else:
cur = cur.next
return dummy.next
相关文章推荐
- LeetCode 147 — Insertion Sort List(C++ Java Python)
- [LeetCode]题解(python):147-Insertion Sort List
- [leetcode] Insertion Sort List(python)
- [leetcode]Insertion Sort List @ Python
- leetcode 【 Insertion Sort List 】 python 实现
- 【LeetCode with Python】 Insertion Sort List
- [Leetcode][python]Insertion Sort List
- 【LEETCODE】147- Insertion Sort List [Python]
- Insertion Sort List Leetcode Python
- [leetcode] Insertion Sort List(python)
- leetcode - Insertion Sort List
- leetcode 133: Insertion Sort List
- Leetcode Insertion Sort List 解题报告
- Insertion Sort List | leetcode
- [Leetcode] Insertion Sort List (Java)
- LeetCode | Insertion Sort List
- Leetcode: Insertion Sort List
- [leetcode]Insertion Sort List
- LeetCode - Insertion Sort List
- LeetCode:Insertion Sort List