LeetCode每日一题:分割链表

2017-05-17  本文已影响22人  yoshino

问题描述

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;
    }
上一篇下一篇

猜你喜欢

热点阅读