86. Partition List

发布时间:2019-06-04 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了86. Partition List脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

难度:medium

题目:给定链表和一指定值X,以X为参照将链表划分为小于X和大于等于X两部分。保持原始链表中结点的顺序不变。

思路:将原始链表先拆分为两链表,一个收集所以小于X的,一个收集其它的。然后合并两链表。

Runtime: 0 ms, faster than 100.00% of Java online submissions for Partition List.
Memory Usage: 36.7 MB, less than 0.90% of Java online submissions for Partition List.

/**
 * 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 lHead = new ListNode(0), lTail = lHead;
        ListNode geHead = new ListNode(0), geTail = geHead;
        ListNode ptr = head, node = null;
        while (ptr != null) {
            node = ptr;
            ptr = ptr.next;
            if (node.val < x) {
                lTail.next = node;
                lTail = node;
            } else {
                geTail.next = node;
                geTail = node;
            }
        }
        
        lTail.next = geHead.next;
        geTail.next = null;
        
        return lHead.next;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的86. Partition List全部内容,希望文章能够帮你解决86. Partition List所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: