[leetcode] 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的node往前插。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(!head) return head;
        ListNode* res = new ListNode(0);
        res->next = head; 

        ListNode* tail = res, *pre = res, *cur = head;  
        while(cur){
            ListNode* next = cur->next;
            if(cur->val>=x){
                pre = cur;
                cur = next;
            }else{
                if(tail->next!=cur){
                    cur->next = tail->next;
                    tail->next = cur;
                    pre->next = next;
                    tail = cur;
                    cur = next;
                }else{
                    tail = cur;
                    pre = cur;
                    cur = next;
                }
            }
        }
        return res->next;
    }
};


解法二:

更簡潔一些。主要是多看一位,即判斷cur->next->val的大小。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* pre = dummy;
        while(pre->next&&pre->next->val<x) pre = pre->next;
        ListNode* cur = pre;
        
        while(cur->next){
            if(cur->next->val>=x){
                cur = cur->next;
            }else{
                ListNode* next = cur->next;
                cur->next = next->next;
                next->next = pre->next;
                pre->next = next;
                pre = pre->next;
            }
        }
        return dummy->next;
        
    }
};



發佈了31 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章