LC 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.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

We keep two heads: one for nodes smaller than x, one for >= x.
We will iterate through the list and put things into the right Linked list.
In the end, we will point to tail of linked list < target to the head of linked list >= target

Make copy

Not make copy

Can we just repoint everybody and not break anything?

Yes since the current pointer will always be at least 1 ahead of both sPtr and gePtr so any alteration of sPtr -> next and gePtr -> next will not change the list after it.

/**
 * 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 dummyHead(-1);
        ListNode sHead(-1);
        ListNode geHead(-1);
        ListNode *sPtr = &sHead;
        ListNode *gePtr = &geHead;
        ListNode *ptr = head;
        while(ptr != NULL){
            if (ptr -> val < x){
                sPtr -> next = ptr;
                sPtr = ptr;
            }
            else{
                gePtr -> next = ptr;
                gePtr = ptr;
            }
            ptr = ptr -> next;
        }

        sPtr -> next = geHead.next;
        gePtr -> next = NULL;
        return sHead.next;   
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax