1. 程式人生 > >96. Partition List [easy]

96. Partition List [easy]

lse reserve 哈哈哈 style nodes scrip 插入代碼 should 大於等於

Description

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.

Example

Given 1->4->3->2->5->2->null and x = 3,
return 1->2->2->4->3->5->null

.

看到“partition”,還以為是快速排序呢。。。題目的意思是,給一個鏈表,再給一個數。將鏈表中的數分為兩個類:小於x、大於等於x。返回值為該類型的ListNode,將小於x的放前面,大於等於x的,放在後面。先貼給圖:

技術分享圖片

哈哈哈,其實思路也挺簡單的,不知道怎麽就成最快的了。

思路:按照我分析的,將原鏈表拆分成兩個鏈表,最後再合並起來。代碼如下:

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 
*/ public class Solution { /** * @param head: The first node of linked list * @param x: An integer * @return: A ListNode */ public ListNode partition(ListNode head, int x) { // write your code here //放值小於x的結點,lp為插入low鏈表時的尾指針 ListNode low=null; ListNode lp
=low; //放值大於等於x的結點,hp為插入high鏈表時的尾指針 ListNode high=null; ListNode hp=high; //p為循環的遊標 ListNode p=head; while(p!=null){ if(p.val<x){ //註意,low是不是空的插入代碼是不同的,如果low為空 //直接lp.next會報錯 if(low==null){ low=p; lp=low; p=p.next; lp.next=null; }else{ lp.next=p; p=p.next; lp=lp.next; lp.next=null; } }else{ if(high==null){ high=p; hp=high; p=p.next; hp.next=null; }else{ hp.next=p; p=p.next; hp=hp.next; hp.next=null; } } } //如果沒有比x小的 if(low==null){ return high; } //如果沒有大於等於x的 if(high==null){ return low; } //如果都有 lp.next=high; return low; } }

96. Partition List [easy]