File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Definition for singly-linked list.
2
+ # Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
3
+ # You should preserve the original relative order of the nodes in each of the two partitions.
4
+ # Given 1->4->3->2->5->2 and x = 3,
5
+ # return 1->2->2->4->3->5.
6
+
7
+
8
+ #思路
9
+ #设置两个guardnode
10
+ #然后制造两个temp node用于循环
11
+ #将第一个链表的末尾指向第二个的开头,返还第一个guardnode.next
12
+
13
+ class Solution(object):
14
+ def partition(self, head, x):
15
+ small, large = ListNode(0), ListNode(0)
16
+ cur1, cur2 = small, large
17
+
18
+ while head:
19
+ if head.val < x:
20
+ cur1.next = head
21
+ cur1 = cur1.next
22
+ else:
23
+ cur2.next = head
24
+ cur2 = cur2.next
25
+
26
+ head = head.next
27
+
28
+ cur2.next = None
29
+ cur1.next = large.next
30
+
31
+ return small.next
You can’t perform that action at this time.
0 commit comments