86. Partition List

Description

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,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

Solution

Two-pointers

比較簡(jiǎn)單的做法是把節(jié)點(diǎn)移動(dòng)到兩個(gè)新鏈表中,最后把兩個(gè)新鏈表拼起來。注意不要形成環(huán)。


/**
 * 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 smallHead = new ListNode(0);
        ListNode largeHead = new ListNode(0);
        ListNode smallTail = smallHead;
        ListNode largeTail = largeHead;

        while (head != null) {
            if (head.val < x) {
                smallTail.next = head;
                smallTail = smallTail.next;
            } else {
                largeTail.next = head;
                largeTail = largeTail.next;
            }
            head = head.next;
        }

        smallTail.next = largeHead.next;
        largeTail.next = null;  // in case there's a loop
        return smallHead.next;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 重新整理了一下以前寫過的小Demo,收錄了部分整合在來一起 效果圖: 源代碼:https://github.com...
    ShenYj閱讀 274評(píng)論 0 1
  • 今天是大寒也是小年溫度在寒風(fēng)的吹拂下迅速降低到零下一早趕去公司做收尾工作為公司收垃圾多年的老許特地買了蘋果和核桃說...
    哈哈同學(xué)閱讀 169評(píng)論 0 0
  • 首先將PC和UR3用網(wǎng)線連接并把ip分別設(shè)置為192.168.1.1和192.168.1.2。安裝ur_morde...
    王啟凡閱讀 1,575評(píng)論 0 0