[leetcode] Partition List


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.

一开始没看懂题意,其实是把原链表分成两个链表,再接到一起。

直接维护两个链表,smaller和greater,one-pass就好。

我用到了superHead的思路,注意最后要delete掉superHead以防止内存溢出。

/**
 * 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 * smaller = new ListNode(0);
        ListNode * greater = new ListNode(0);
        ListNode * p = smaller;
        ListNode * q = greater;
        while(head != NULL){
            if(head->val < x){
                p->next = head;
                p = p->next;
            }
            else{
                q->next = head;
                q = q->next;
            }
            head = head->next;
        }
        p->next = greater->next;
        q->next = NULL;
        p = smaller->next;
        delete smaller, greater;
        return p;
    }
};

 

Untitled

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.