您的位置:首页 > 编程语言 > Java开发

leetcode:Partition List 【Java】

2016-03-11 17:04 239 查看
一、问题描述

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的值。

在建新链表的过程中需要打断原链表中的链。

三、算法代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode partition(ListNode head, int x) {
        if(head == null || head.next == null){
            return head;
        }
        
        ListNode lesser = null, lesserHead = null;
        ListNode greater = null, greaterHeader = null;
        
        ListNode cur = null;
        
        if(head.val < x){
            lesserHead = head;
            lesser = head;
            cur = head.next;
            lesser.next = null;//打断原链表中的链
        }else{
            greaterHeader = head;
            greater = head;
            cur = head.next;
            greater.next = null;//打断原链表中的链
        }
        
        while(cur != null){
            if(cur.val < x){
                if(lesserHead == null){
                    lesserHead = cur;
                    lesser = cur;
                    cur = cur.next;
                    lesser.next = null;//打断原链表中的链
                }else{
                    lesser.next = cur;
                    lesser = lesser.next;
                    cur = cur.next;
                    lesser.next = null; //打断原链表中的链
                }
            }else{
                if(greaterHeader == null){
                    greaterHeader = cur;
                    greater = cur;
                    cur = cur.next;
                    greater.next = null;//打断原链表中的链
                }else{
                    greater.next = cur;
                    greater = greater.next;
                    cur = cur.next;
                    greater.next = null;//打断原链表中的链
                }
            }
        }
        if(lesserHead == null){
            return greaterHeader;
        }else{
            lesser.next = greaterHeader;
            return lesserHead;
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: