1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Partition List

Posted on 2014-01-12 15:07  1957  阅读(118)  评论(0编辑  收藏  举报

最简单的就是用O(n)的额外空间

不过也没必要,就用两个指针就好啦。。

 

/**
 * 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 == nullptr) return head;
        ListNode* left = new ListNode(-1);
        ListNode* right = new ListNode(-1);
        ListNode* lcur = left;
        ListNode* rcur = right;
        ListNode* curr = head;
        while(curr) {
            if(curr -> val < x) {
                lcur -> next = curr;
                lcur = curr;
            } else {
                rcur -> next = curr;
                rcur = curr;
            }
            curr = curr -> next;
        }
        lcur -> next = right -> next;
        rcur -> next = nullptr;
        return left -> next;
    }
};