2.2.3 Partition List

Link: https://oj.leetcode.com/problems/partition-list/

這是CC150原題,我的思路正確,但代碼有問題。再做。

Time: O(n), Space: O(1)

我的代碼:

public class Solution {
    //CC150 
    public ListNode partition(ListNode head, int x) {
        if(head == null) return null;
        ListNode sHead = null;//small
        ListNode sTail = null;
        ListNode lHead = null;//large
        ListNode lTail = null;
        while(head != null){
            if(head.val < x){
                sTail.next = head;
                sTail = sTail.next;
            }
            else{
                lTail.next = head;
                lTail = lTail.next;
            }
            head = head.next;
        }
        sTail.next = lHead;
        return sHead.next;
    }
}

正確答案:

主要錯誤是:

 sTail.next = lHead;
 改成
 sTail.next = lHead.next;

public class Solution {
    //CC150 
    public ListNode partition(ListNode head, int x) {
        if(head == null) return null;
        ListNode sHead = new ListNode(-1);//small
        ListNode sTail = sHead;
        ListNode lHead = new ListNode(-1);//large
        ListNode lTail = lHead;
        while(head != null){
            if(head.val < x){
                sTail.next = head;
                sTail = sTail.next;
            }
            else{
                lTail.next = head;
                lTail = lTail.next;
            }
            head = head.next;
        }
        sTail.next = lHead.next;
        lTail.next = null;
        return sHead.next;
    }
}


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