美文网首页
LeetCode每日一题:分割链表

LeetCode每日一题:分割链表

作者: yoshino | 来源:发表于2017-05-17 10:14 被阅读22次

    问题描述

    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.
    For example,
    Given1->4->3->2->5->2and x = 3,
    return1->2->2->4->3->5.

    问题分析

    这道题就是把链表分割成两部分,新建两条链表,直接遍历一遍原链表,把节点依次放入两条链表中,最后再拼接在一起就行了

    代码实现

    public ListNode partition(ListNode head, int x) {
            if (head == null) return null;
            ListNode preHead1 = new ListNode(Integer.MIN_VALUE);
            ListNode preHead2 = new ListNode(Integer.MIN_VALUE);
            ListNode curNode1 = preHead1;
            ListNode curNode2 = preHead2;
            while (head != null) {
                if (head.val < x) {
                    curNode1.next = head;
                    curNode1 = curNode1.next;
                } else {
                    curNode2.next = head;
                    curNode2 = curNode2.next;
                }
                head = head.next;
            }
            curNode2.next = null;
            curNode1.next = preHead2.next;
            return preHead1.next;
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:分割链表

          本文链接:https://www.haomeiwen.com/subject/pdxdxxtx.html