86. Partition List

栏目: 数据库 · 发布时间: 5年前

内容简介: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 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;
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

产品经理手册(原书第4版)(白金版)

产品经理手册(原书第4版)(白金版)

[美] 琳达·哥乔斯(Linda Gorchels) / 祝亚雄、冯华丽、金骆彬 / 机械工业出版社 / 2017-8 / 65.00

产品经理的职责起点是新产品开发,贯穿产品生命周期的全过程。本书按上下游产品管理进行组织。 在上游的新产品开发流程中,作者阐述了如何从市场、产品、行业、公司的角度规划企划方案,并获得老板、销售部、运营部的资源支持,推进新产品的项目流程,实现所有目标,制定和实施新产品发布。 下游产品的管理核心在于生命周期的管理,营销更是生命周期管理的重中之重。产品经理如何让产品满足客户需求,让客户获得对产......一起来看看 《产品经理手册(原书第4版)(白金版)》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具