[LeetCode-JAVA] Partition List

题目:

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为划分的两段链表,并连接在一起,注意维护链表头。

 

代码:

public class Solution {
    public ListNode partition(ListNode head, int x) {
                ListNode small = new ListNode(0);  //两个新链表
        ListNode big = new ListNode(0);  
        
        ListNode smallTemp = small;   //保存链表头
        ListNode bigTemp = big;
        
        while(head!=null){
            if(head.val < x){
                big.next = head;
                big = big.next;
            }else{
                small.next = head;
                small = small.next;
            }
            head = head.next;
        }
        big.next = smallTemp.next;   //连接
        small.next = null;
        
        return bigTemp.next;
    }
}    

 

posted @ 2015-05-18 17:57  可爱的波儿胖  阅读(158)  评论(0编辑  收藏  举报

友情链接 : CodeForge源码分享