| 標題: | Partition List |
| 通過率: | 27.5% |
| 難度: | 中等 |
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 .
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given?
1->4->3->2->5->2
?and?
x
?= 3,
return?
1->2->2->4->3->5
.
本題就是利用一個target將鏈表分成兩部分,小于target和大于target的
用兩個鏈表進行記錄,small和big進行連接時候一定要將.next置null,否則內存會一直疊加。連接的過程就是指針的重定向過程,所以一定要置null,要不然會講整個鏈表連接過來,代碼如下:
1
/**
2
* Definition for singly-linked list.
3
* public class ListNode {
4
* int val;
5
* ListNode next;
6
* ListNode(int x) {
7
* val = x;
8
* next = null;
9
* }
10
* }
11
*/
12
public
class
Solution {
13
public
ListNode partition(ListNode head,
int
x) {
14
ListNode small=
new
ListNode(1
);
15
ListNode big=
new
ListNode(1
);
16
ListNode s=small,b=
big;
17
if
(head==
null
)
return
head;
18
while
(head!=
null
){
19
if
(head.val<
x){
20
s.next=
head;
21
head=
head.next;
22
s=
s.next;
23
s.next=
null
;
24
}
25
else
{
26
b.next=
head;
27
head=
head.next;
28
b=
b.next;
29
b.next=
null
;
30
}
31
}
32
s.next=
big.next;
33
return
small.next;
34
}
35
}
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

