標(biāo)題: | Partition List |
通過(guò)率: | 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
.
本題就是利用一個(gè)target將鏈表分成兩部分,小于target和大于target的
用兩個(gè)鏈表進(jìn)行記錄,small和big進(jìn)行連接時(shí)候一定要將.next置null,否則內(nèi)存會(huì)一直疊加。連接的過(guò)程就是指針的重定向過(guò)程,所以一定要置null,要不然會(huì)講整個(gè)鏈表連接過(guò)來(lái),代碼如下:
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 }
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
