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.


比x小的尾插,比x大的直接插入,但是小於x的會逆序 導致wrong answer

/**
 * 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) return head ;
        ListNode begin = new ListNode(-1);
        ListNode tail = begin;
        ListNode cur = head;
        ListNode temp = null;
        while(cur!=null){
            if(cur.val>=x){
                temp = cur;
                cur = cur.next;
                tail.next = temp;
                tail = tail.next;
            }else{
                temp = cur;
                cur = cur.next;
                if(begin.next==null){
                    ListNode node = new ListNode(temp.val);
                    begin.next = node;
                    tail = node;
                }else{
                    temp.next = begin.next;
                    begin.next = temp;
                }
            }
        }
        return begin.next;
    }
}


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