Skip to content

Commit e22173b

Browse files
committedJan 29, 2015
Sort a linked list using insertion sort
1 parent 0694ff2 commit e22173b

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
 

‎insertion_sort_list.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
# Definition for singly-linked list.
4+
class ListNode:
5+
def __init__(self, x):
6+
self.val = x
7+
self.next = None
8+
9+
class Solution:
10+
# @param head, a ListNode
11+
# @return a ListNode
12+
def insertionSortList(self, head):
13+
if None == head:
14+
return None
15+
#记录尾部节点
16+
tail_node = head
17+
next_node = head.next
18+
while None != next_node:
19+
if head.val >= next_node.val:
20+
## 更新头指针和next_node
21+
tmp = next_node.next
22+
next_node.next = head
23+
head = next_node
24+
next_node = tmp
25+
elif tail_node.val <= next_node.val:
26+
#小于或等于尾部节点
27+
tail_node.next = next_node
28+
tail_node = next_node
29+
next_node = next_node.next
30+
else:
31+
#从头部查找合适位置进行插入操作
32+
tmp = head.next
33+
prev = head
34+
while None != tmp:
35+
if tmp.val > next_node.val:
36+
break;
37+
prev = tmp
38+
tmp = tmp.next
39+
prev.next = next_node
40+
next_node = next_node.next
41+
prev.next.next = tmp
42+
tail_next = next_node #None
43+
return head
44+
45+
46+
if __name__ == "__main__":
47+
s = Solution()
48+
head = ListNode(4)
49+
node_1 = ListNode(1)
50+
head.next = node_1
51+
52+
node_2 = ListNode(3)
53+
node_1.next = node_2
54+
55+
node_3 = ListNode(5)
56+
node_2.next = node_3
57+
58+
node_4 = ListNode(9)
59+
node_3.next = node_4
60+
61+
node_5 = ListNode(2)
62+
node_4.next = node_5
63+
64+
node_6 = ListNode(8)
65+
node_5.next = node_6
66+
67+
node_7 = ListNode(13)
68+
node_6.next = node_7
69+
70+
node = s.insertionSortList(head)
71+
72+
while None != node:
73+
print node.val
74+
node = node.next
75+
76+

0 commit comments

Comments
 (0)
Please sign in to comment.