Partition List leetcode java


題目

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.

 

題解

這道題就是說給定一個x的值,小於x都放在大於等於x的前面,並且不改變鏈表之間node原始的相對位置。每次看這道題我老是繞暈,糾結為什么4在3的前面。。其實還是得理解題意,4->3->5都是大於等3的數,而且這保持了他們原來的相對位置 。

所以,這道題是不需要任何排序操作的,題解方法很巧妙。

new兩個新鏈表,一個用來創建所有大於等於x的鏈表,一個用來創建所有小於x的鏈表。

遍歷整個鏈表時,當當前node的val小於x時,接在小鏈表上,反之,接在大鏈表上。這樣就保證了相對順序沒有改變,而僅僅對鏈表做了與x的比較判斷。

最后,把小鏈表接在大鏈表上,別忘了把大鏈表的結尾賦成null。

 代碼如下:

 1      public ListNode partition(ListNode head,  int x) {
 2          if(head== null||head.next== null)
 3              return head;
 4         
 5         ListNode small =  new ListNode(-1);
 6         ListNode newsmallhead = small;
 7         ListNode big =  new ListNode(-1);
 8         ListNode newbighead = big;
 9         
10          while(head!= null){
11              if(head.val<x){
12                 small.next = head;
13                 small = small.next;
14             } else{
15                 big.next = head;
16                 big = big.next;
17             }
18             head = head.next;
19         }
20         big.next =  null;
21         
22         small.next = newbighead.next;
23         
24          return newsmallhead.next;
25     }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM