首页 > 其他 > 详细

leetcode [86]Partition List

时间:2019-04-09 14:48:44      阅读:155      评论:0      收藏:0      [点我收藏+]

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:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

题目大意:

将LinkedList利用partition划分为两个部分,LinkedList的前半部分都是比给定的x要小的值,而后半部分是比给定值要大的值。

解法:

将该链表一分为二,分成两个链表,最后再将两个链表串起来。链表一存放的都是比value值要小的节点,而链表二存放的都是比value值要大的节点。

java:

class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode h1=new ListNode(0);
        ListNode h2=new ListNode(0);
        ListNode head1=h1,head2=h2;
        while(head!=null){
            if(head.val<x){
                head1.next=head;
                head1=head1.next;
            }else{
                head2.next=head;
                head2=head2.next;
            }
            head=head.next;
        }
        head2.next=null;
        head1.next=h2.next;

        return h1.next;
    }
}

  

leetcode [86]Partition List

原文:https://www.cnblogs.com/xiaobaituyun/p/10676618.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!