Leetcode: 86. Partition List

Description

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.

Example

Given 1->4->3->2->5->2 and x = 3,

return 1->2->2->4->3->5.

思路

  • 维护一个结果链表,tmp指向结果链表的表尾,ptr指向结果链表中小于给定x的最后一个数,然后遍历原链表,大于等于x的接到tmp后面,重置tmp。小于x的插入到ptr后面,然后ptr往后走一步,最后记得将表尾置为NULL

代码

/**
 * 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 NULL;
        
        ListNode *cur = head;
        ListNode *res = new ListNode(0);
        ListNode *ptr = res, *next = NULL;
        ListNode *tmp = res;
        while(cur){
           next = cur->next;
           if(cur->val < x){
                if(cur != ptr->next)
                    cur->next = ptr->next;
                ptr->next = cur;
                if(tmp == ptr)
                    tmp = ptr->next;
                ptr = ptr->next;
           } 
           else{
               tmp->next = cur;
               tmp = tmp->next;
           }
           cur = next;
        }
        
        tmp->next = NULL;
        head = res->next;
        delete res;
        return head;
    }
};
posted @ 2017-06-14 10:50  JeffLai  阅读(229)  评论(0编辑  收藏  举报