算法之鏈表分割鏈表

問題描述

編寫程序以 x 爲基準分割鏈表,使得所有小於 x 的節點排在大於或等於 x 的節點之前。如果鏈表中包含 x,x 只需出現在小於 x 的元素之後(如下所示)。分割元素 x 只需處於“右半部分”即可,其不需要被置於左右兩部分之間。

示例:

輸入: head = 3->5->8->5->10->2->1, x = 5
輸出: 3->1->2->10->5->5->8

解決辦法

class Solution {
    /**
    * 3->5->8->5->10->2->1, x = 5
    * 本質上是將小於的結點放在鏈表的前面即可
    */
    public ListNode partition(ListNode head, int x) {
        if(head == null)
            return null;
        ListNode current = head;
        //注意,這裏的遍歷,忽略了第一個結點。
        //但是在將小於X結點插入到鏈表頭部的過程中,原有第一個結點
        //始終保持在“新插入結點的尾部“
        while(current.next!=null){
            if(current.next.val<x){
                //將current.next往頭部
                ListNode tmp = current.next;
                //刪除currentNext結點
                current.next = current.next.next;
                //將currentNext結點放入頭部
                tmp.next= head;
                head = tmp;
            }else{
                current = current.next;
            }
        }
        return head;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章