Skip to content

Commit 0bba2e6

Browse files
author
weiy
committed
partition list medium
1 parent 8216fa6 commit 0bba2e6

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Array/PartitionList.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
"""
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+
4+
You should preserve the original relative order of the nodes in each of the two partitions.
5+
6+
Example:
7+
8+
Input: head = 1->4->3->2->5->2, x = 3
9+
Output: 1->2->2->4->3->5
10+
11+
无脑怼。
12+
13+
beat:
14+
99%.
15+
16+
测试地址:
17+
https://leetcode.com/problems/partition-list/description/
18+
"""
19+
# Definition for singly-linked list.
20+
# class ListNode(object):
21+
# def __init__(self, x):
22+
# self.val = x
23+
# self.next = None
24+
25+
class Solution(object):
26+
def partition(self, head, x):
27+
"""
28+
:type head: ListNode
29+
:type x: int
30+
:rtype: ListNode
31+
"""
32+
33+
all_nodes = []
34+
35+
while head:
36+
all_nodes.append(head.val)
37+
head = head.next
38+
39+
less_nodes = []
40+
greater_nodes = []
41+
42+
for i in all_nodes:
43+
if i < x:
44+
less_nodes.append(i)
45+
else:
46+
greater_nodes.append(i)
47+
48+
if less_nodes:
49+
less_head = ListNode(less_nodes[0])
50+
51+
head = less_head if less_nodes else None
52+
53+
for i in less_nodes[1:]:
54+
less_head.next = ListNode(i)
55+
less_head = less_head.next
56+
57+
if greater_nodes:
58+
greater_head = ListNode(greater_nodes[0])
59+
60+
_head = greater_head if greater_nodes else None
61+
62+
for i in greater_nodes[1:]:
63+
greater_head.next = ListNode(i)
64+
greater_head = greater_head.next
65+
66+
if head:
67+
less_head.next = _head
68+
69+
return head
70+
return _head
71+

0 commit comments

Comments
 (0)