Skip to content

Commit f5150fe

Browse files
committed
86 update
1 parent e67ba92 commit f5150fe

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

linkedlist/PartitionLinkedList.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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

0 commit comments

Comments
 (0)