码迷,mamicode.com
首页 > 其他好文 > 详细

96. Partition List [easy]

时间:2018-05-21 21:16:48      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:插入代码   返回值   哈哈哈   等于   linked   desc   end   返回   app   

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]

标签:插入代码   返回值   哈哈哈   等于   linked   desc   end   返回   app   

原文地址:https://www.cnblogs.com/phdeblog/p/9069138.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!