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.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

這道題沒(méi)看答案之前不明白到底如何移動(dòng),看了答案發(fā)現(xiàn)太簡(jiǎn)單了。new兩個(gè)鏈表,遍歷原鏈表,把val大于等于x的節(jié)點(diǎn)接到big后面,把val小于x的節(jié)點(diǎn)接到small后面,最后把big接到small后面,就可以了。

WechatIMG53.jpeg
/**
 * 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) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode big = new ListNode(-1);
        ListNode small = new ListNode(-1);
        ListNode bighead = big;
        ListNode smallhead = small;
        while (head != null){
            if (head.val < x){
                smallhead.next = head;
                smallhead = smallhead.next;
            } else {
                bighead.next = head;
                bighead = bighead.next;
            }
            head = head.next;
        }
        bighead.next = null;
        smallhead.next = big.next;
        return small.next;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容