34
34
35
35
class Solution :
36
36
def partition (self , head : ListNode, x : int ) -> ListNode:
37
- if head is None or head.next is None :
38
- return head
39
- left, right = ListNode(- 1 ), ListNode(- 1 )
40
- p, q = left, right
37
+ l1, l2 = ListNode(0 ), ListNode(0 )
38
+ cur1, cur2 = l1, l2
41
39
while head:
42
- t = head.next
43
- head.next = None
44
40
if head.val < x:
45
- p .next = head
46
- p = p .next
41
+ cur1 .next = head
42
+ cur1 = cur1 .next
47
43
else :
48
- q.next = head
49
- q = q.next
50
- head = t
51
- p.next = right.next
52
- return left.next
44
+ cur2.next = head
45
+ cur2 = cur2.next
46
+ head = head.next
47
+ cur1.next = l2.next
48
+ cur2.next = None
49
+ return l1.next
53
50
```
54
51
55
52
### ** Java**
@@ -62,35 +59,70 @@ class Solution:
62
59
* public class ListNode {
63
60
* int val;
64
61
* ListNode next;
65
- * ListNode(int x) { val = x; }
62
+ * ListNode() {}
63
+ * ListNode(int val) { this.val = val; }
64
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
66
65
* }
67
66
*/
68
67
class Solution {
69
68
public ListNode partition (ListNode head , int x ) {
70
- if (head == null || head. next == null ) {
71
- return head;
72
- }
73
- ListNode left = new ListNode (- 1 );
74
- ListNode right = new ListNode (- 1 );
75
- ListNode p = left, q = right;
69
+ ListNode l1 = new ListNode (0 );
70
+ ListNode l2 = new ListNode (0 );
71
+ ListNode cur1 = l1, cur2 = l2;
76
72
while (head != null ) {
77
- ListNode t = head. next;
78
- head. next = null ;
79
73
if (head. val < x) {
80
- p . next = head;
81
- p = p . next;
74
+ cur1 . next = head;
75
+ cur1 = cur1 . next;
82
76
} else {
83
- q . next = head;
84
- q = q . next;
77
+ cur2 . next = head;
78
+ cur2 = cur2 . next;
85
79
}
86
- head = t ;
80
+ head = head . next ;
87
81
}
88
- p. next = right. next;
89
- return left. next;
82
+ cur1. next = l2. next;
83
+ cur2. next = null ;
84
+ return l1. next;
90
85
}
91
86
}
92
87
```
93
88
89
+ ### ** C++**
90
+
91
+ ``` cpp
92
+ /* *
93
+ * Definition for singly-linked list.
94
+ * struct ListNode {
95
+ * int val;
96
+ * ListNode *next;
97
+ * ListNode() : val(0), next(nullptr) {}
98
+ * ListNode(int x) : val(x), next(nullptr) {}
99
+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
100
+ * };
101
+ */
102
+ class Solution {
103
+ public:
104
+ ListNode* partition(ListNode* head, int x) {
105
+ ListNode* l1 = new ListNode();
106
+ ListNode* l2 = new ListNode();
107
+ ListNode* cur1 = l1;
108
+ ListNode* cur2 = l2;
109
+ while (head != nullptr) {
110
+ if (head->val < x) {
111
+ cur1->next = head;
112
+ cur1 = cur1->next;
113
+ } else {
114
+ cur2->next = head;
115
+ cur2 = cur2->next;
116
+ }
117
+ head = head->next;
118
+ }
119
+ cur1->next = l2->next;
120
+ cur2->next = nullptr;
121
+ return l1->next;
122
+ }
123
+ };
124
+ ```
125
+
94
126
### **...**
95
127
96
128
```
0 commit comments