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

leetcode86 - Partition List - medium

时间:2018-10-04 10:55:20      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:pre   tno   记录   should   next   and   solution   lin   amp   

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

 

模拟题。
1.用链1记录所有<x的nodes。
2.用链2记录所有>=x的nodes。
3.合并链1链2.

细节:
1.需要dummy1, dummy2, p1, p2。dummy.next指着链的头。p1 p2指着当前链延伸情况下的最后一个node。

 

实现:

/**
 * 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) {
        // 1. find nodes < x, dummynode1 
        // 2. find nodes >= x, dummynode2
        // 3. connect two links
        ListNode dummy1 = new ListNode(-1);
        ListNode dummy2 = new ListNode(-1);
        ListNode p1 = dummy1, p2 = dummy2;
        while (head != null) {
            if (head.val < x) {
                p1.next = head;
                p1 = p1.next;
            } else {
                p2.next = head;
                p2 = p2.next;
            }
            head = head.next;
        }
        p1.next = dummy2.next;
        p2.next = null;
        return dummy1.next;
    }
}

 

leetcode86 - Partition List - medium

标签:pre   tno   记录   should   next   and   solution   lin   amp   

原文地址:https://www.cnblogs.com/jasminemzy/p/9739597.html

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