JAVA OJ練習第6題——鏈表分割

牛客鏈接:鏈表分割

編寫代碼,以給定值x爲基準將鏈表分割成兩部分,所有小於x的結點排在大於或等於x的結點之前且原順序不變

思維邏輯圖如下:
先將<x的數字排成一個新鏈表,將>x的數字拍成一個新鏈表,最後將這兩個鏈表連在一起即可。
bs:<x新鏈表的頭(b start);
be:<x新鏈表的尾(b end);
as:>x新鏈表的頭(b start);
ae:>x新鏈表的尾(b end);
將兩個新鏈表連在一起只需讓be指向as即可。
在這裏插入圖片描述

代碼如下:

public class Partition {
    public ListNode partition(ListNode pHead, int x) {
        ListNode cur = pHead;
        ListNode bs = null;
        ListNode be = null;
        ListNode as = null;
        ListNode ae = null;
        while(cur != null) {
            if(cur.val < x) {
                //判斷是不是第一次插入
                if(bs == null) {
                    bs = cur;
                    be = bs;
                }else {
                    be.next = cur;
                    be = be.next;//be = cur;
                }
            }else {
                //判斷是不是第一次插入
                if(as == null) {
                    as = cur;
                    ae = cur;
                }else {
                    ae.next = cur;
                    ae = ae.next;//ae = cur;
                }
            }
            cur = cur.next;
        }
        if(bs == null){
            return as;
        }
        be.next = as;
        if(as != null) {
            ae.next = null;
        }
        return bs;
    }
}

下一題:刪除鏈表中重複的結點
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章