File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed
algorithm/LeetCode/Linked-List Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 205
205
- [ Length of Last Word] ( /algorithm/LeetCode/String/Length-of-Last-Word.md )
206
206
- [ Linked List] ( /algorithm/LeetCode/Linked-List.md )
207
207
- [ Remove Duplicates from Sorted List] ( /algorithm/LeetCode/Linked-List/Remove-Duplicates-from-Sorted-List.md )
208
+ - [ Partition List] ( /algorithm/LeetCode/Linked-List/Partition-List.md )
208
209
209
210
## 设计模式
210
211
Original file line number Diff line number Diff line change
1
+ ## 一、题目
2
+
3
+ > 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* .
4
+ >
5
+ > You should preserve the original relative order of the nodes in each of the two partitions.
6
+ >
7
+ > For example,
8
+ > Given ` 1->4->3->2->5->2 ` and * x* = 3,
9
+ > return ` 1->2->2->4->3->5 ` .
10
+
11
+ 给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
12
+
13
+ 你应该保留两部分内链表节点原有的相对顺序。
14
+
15
+ ## 二、解题思路
16
+
17
+ 依据题意,是要根据值x对链表进行分割操作,具体是指将所有小于x的节点放到不小于x的节点之前,咋一看和快速排序的分割有些类似,但是这个题的不同之处在于只要求将小于x的节点放到前面,而并不要求对元素进行排序。
18
+
19
+ 这种分割的题使用两路指针即可轻松解决。左边指针指向小于x的节点,右边指针指向不小于x的节点。由于左右头节点不确定,我们可以使用两个dummy节点。
20
+
21
+ ## 三、解题代码
22
+
23
+ ``` java
24
+ /**
25
+ * Definition for singly-linked list.
26
+ * public class ListNode {
27
+ * int val;
28
+ * ListNode next;
29
+ * ListNode(int x) { val = x; }
30
+ * }
31
+ */
32
+ public class Solution {
33
+ public ListNode partition (ListNode head , int x ) {
34
+ ListNode leftDummy = new ListNode (0 );
35
+ ListNode leftCurr = leftDummy;
36
+ ListNode rightDummy = new ListNode (0 );
37
+ ListNode rightCurr = rightDummy;
38
+
39
+ ListNode runner = head;
40
+ while (runner != null ) {
41
+ if (runner. val < x) {
42
+ leftCurr. next = runner;
43
+ leftCurr = leftCurr. next;
44
+ } else {
45
+ rightCurr. next = runner;
46
+ rightCurr = rightCurr. next;
47
+ }
48
+ runner = runner. next;
49
+ }
50
+
51
+ // cut off ListNode after rightCurr to avoid cylic
52
+ rightCurr. next = null ;
53
+ leftCurr. next = rightDummy. next;
54
+
55
+ return leftDummy. next;
56
+ }
57
+ }
58
+ ```
59
+
You can’t perform that action at this time.
0 commit comments