Skip to content

Commit ca10134

Browse files
Add files via upload
1 parent 01e390a commit ca10134

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// 链表的插入排序
2+
3+
// Runtime: 48 ms, faster than 75.93% of C++ online submissions for Insertion Sort List.
4+
// Memory Usage: 9.5 MB, less than 100.00% of C++ online submissions for Insertion Sort List.
5+
6+
/**
7+
* Definition for singly-linked list.
8+
* struct ListNode {
9+
* int val;
10+
* ListNode *next;
11+
* ListNode(int x) : val(x), next(NULL) {}
12+
* };
13+
*/
14+
15+
class Solution
16+
{
17+
public:
18+
ListNode* insertionSortList(ListNode* head)
19+
{
20+
// 如果只有一个元素或者没有元素的话直接返回即可,不需要排序
21+
if (head == 0 || head->next == 0)
22+
return head;
23+
24+
for (ListNode *preNode = 0, *curNode = head, *nextNode = head; curNode; curNode = nextNode)
25+
{
26+
nextNode = nextNode->next;
27+
28+
// 迭代寻找适合的插入位置
29+
ListNode *leftNode = 0, *rightNode = head;
30+
bool insert = false;
31+
while (rightNode != curNode)
32+
{
33+
if (rightNode->val <= curNode->val)
34+
{
35+
leftNode = rightNode;
36+
rightNode = rightNode->next;
37+
}
38+
else
39+
{
40+
insert = true;
41+
curNode->next = rightNode;
42+
43+
if (leftNode)
44+
leftNode->next = curNode;
45+
else
46+
head = curNode;
47+
48+
preNode->next = nextNode;
49+
break;
50+
}
51+
}
52+
53+
if (!insert)
54+
preNode = curNode;
55+
}
56+
return head;
57+
}
58+
};
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Runtime: 1324 ms, faster than 50.00% of Python3 online submissions for Insertion Sort List.
2+
# Memory Usage: 14.6 MB, less than 100.00% of Python3 online submissions for Insertion Sort List.
3+
4+
# Definition for singly-linked list.
5+
# class ListNode:
6+
# def __init__(self, x):
7+
# self.val = x
8+
# self.next = None
9+
10+
class Solution:
11+
def insertionSortList(self, head: 'ListNode') -> 'ListNode':
12+
if head is None or head.next is None:
13+
return head
14+
15+
preNode, curNode, nextNode = None, head, head
16+
while curNode:
17+
nextNode = nextNode.next
18+
19+
leftNode, rightNode = None, head
20+
insert = False
21+
while rightNode != curNode:
22+
if rightNode.val <= curNode.val:
23+
leftNode = rightNode
24+
rightNode = rightNode.next
25+
else:
26+
insert = True
27+
curNode.next = rightNode
28+
29+
if leftNode:
30+
leftNode.next = curNode
31+
else:
32+
head = curNode
33+
34+
preNode.next = nextNode
35+
break
36+
37+
if not insert:
38+
preNode = curNode
39+
40+
curNode = nextNode
41+
42+
return head

0 commit comments

Comments
 (0)