37
37
Java Code:
38
38
39
39
``` java
40
- /**
41
- * Definition for singly-linked list.
42
- * public class ListNode {
43
- * int val;
44
- * ListNode next;
45
- * ListNode(int x) { val = x; }
46
- * }
47
- */
48
40
class Solution {
49
41
public ListNode partition (ListNode head , int x ) {
50
- if (head == null ) {
51
- return head;
52
- }
53
42
ListNode pro = head;
54
43
ListNode big = new ListNode (- 1 );
55
44
ListNode small = new ListNode (- 1 );
56
45
ListNode headbig = big;
57
- ListNode headsmall = small;
58
- // 分
59
- while (pro != null ) {
46
+ ListNode headsmall = small;
47
+ // 分
48
+ while (pro != null ) {
60
49
// 大于时,放到 big 链表上
61
50
if (pro. val >= x) {
62
51
big. next = pro;
63
52
big = big. next;
64
- // 小于放到 small 链表上
53
+ // 小于时,放到 small 链表上
65
54
}else {
66
55
small. next = pro;
67
56
small = small. next;
@@ -83,21 +72,18 @@ C++ Code:
83
72
class Solution {
84
73
public:
85
74
ListNode* partition(ListNode* head, int x) {
86
- if (head == nullptr) {
87
- return head;
88
- }
89
75
ListNode * pro = head;
90
76
ListNode * big = new ListNode(-1);
91
77
ListNode * small = new ListNode(-1);
92
78
ListNode * headbig = big;
93
- ListNode * headsmall =small;
94
- //分
95
- while (pro != nullptr) {
79
+ ListNode * headsmall = small;
80
+ //分
81
+ while (pro != nullptr) {
96
82
//大于时,放到 big 链表上
97
83
if (pro->val >= x) {
98
84
big->next = pro;
99
85
big = big->next;
100
- // 小于放到 small 链表上
86
+ //小于时,放到 small 链表上
101
87
}else {
102
88
small->next = pro;
103
89
small = small->next;
@@ -113,5 +99,65 @@ public:
113
99
};
114
100
```
115
101
102
+ JS Code:
103
+
104
+ ```js
105
+ var partition = function(head, x) {
106
+ let pro = head;
107
+ let big = new ListNode(-1);
108
+ let small = new ListNode(-1);
109
+ let headbig = big;
110
+ let headsmall = small;
111
+ //分
112
+ while (pro) {
113
+ //大于时,放到 big 链表上
114
+ if (pro.val >= x) {
115
+ big.next = pro;
116
+ big = big.next;
117
+ //小于时,放到 small 链表上
118
+ }else {
119
+ small.next = pro;
120
+ small = small.next;
121
+ }
122
+ pro = pro.next;
123
+ }
124
+ //细节
125
+ big.next = null;
126
+ //合
127
+ small.next = headbig.next;
128
+ return headsmall.next;
129
+ };
130
+ ```
116
131
117
-
132
+ Python Code:
133
+
134
+ ``` py
135
+ # Definition for singly-linked list.
136
+ # class ListNode:
137
+ # def __init__(self, val=0, next=None):
138
+ # self.val = val
139
+ # self.next = next
140
+ class Solution :
141
+ def partition (self , head : ListNode, x : int ) -> ListNode:
142
+ pro = head
143
+ big = ListNode(- 1 )
144
+ small = ListNode(- 1 )
145
+ headbig = big
146
+ headsmall = small
147
+ # 分
148
+ while pro is not None :
149
+ # 大于时,放到 big 链表上
150
+ if pro.val >= x:
151
+ big.next = pro
152
+ big = big.next
153
+ # 小于时,放到 small 链表上
154
+ else :
155
+ small.next = pro
156
+ small = small.next
157
+ pro = pro.next
158
+ # 细节
159
+ big.next = None
160
+ # 合
161
+ small.next = headbig.next
162
+ return headsmall.next
163
+ ```
0 commit comments