LeetCode python-147. 对链表进行插入排序
先看题目:
(题目来力扣网站)
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def insertionSortList(self, head):
if not head:
return None
pre = head
cur = head.next
while cur:
if cur.val < pre.val:
pre.next = cur.next
temp = ListNode(0)
temp.next = head
if cur.val < head.val:
head = cur
while temp != pre:
if temp.next.val > cur.val:
cur.next = temp.next
temp.next = cur
break
else:
temp = temp.next
cur = pre.next
else:
pre = cur
cur = cur.next
return head
node1 = ListNode(4)
node2 = ListNode(2)
node3 = ListNode(1)
node4 = ListNode(3)
node1.next = node2
node2.next = node3
node3.next = node4
s = Solution()
node5 = s.insertionSortList(node1)
while(node5):
print(node5.val)
node5 = node5.next