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

86. Partition List

时间:2019-08-10 10:05:20      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:else   str   put   大于   pre   tput   partition   tps   linked   

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
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode small = new ListNode(-1);
        ListNode big = new ListNode(-1);
        ListNode smallhead = small;
        ListNode bighead = big;
        while(head != null){
            if(head.val < x){
                small.next = head;
                small = small.next;
            }
            else{
                big.next = head;
                big = big.next;
            }
            head = head.next;
        }
        big.next = null;
        small.next = bighead.next;
        return smallhead.next;
    }
}

https://www.cnblogs.com/springfor/p/3862392.html

题解: 

这道题就是说给定一个x的值,小于x都放在大于等于x的前面,并且不改变链表之间node原始的相对位置。每次看这道题我老是绕晕,纠结为什么4在3的前面。。其实还是得理解题意,4->3->5都是大于等3的数,而且这保持了他们原来的相对位置 。

所以,这道题是不需要任何排序操作的,题解方法很巧妙。

new两个新链表,一个用来创建所有大于等于x的链表,一个用来创建所有小于x的链表。

遍历整个链表时,当当前node的val小于x时,接在小链表上,反之,接在大链表上。这样就保证了相对顺序没有改变,而仅仅对链表做了与x的比较判断。

最后,把小链表接在大链表上,别忘了把大链表的结尾赋成null。

86. Partition List

标签:else   str   put   大于   pre   tput   partition   tps   linked   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11330364.html

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