86. Partition List

problem descripiton

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

algorithm thought

首先初始化两个头,然后将两个partition,分别加到两个头上,最后将两个partition合并

code

/**
 * 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* tou1=new ListNode(-1);
        tou1->next=head;
        ListNode* tou2=new ListNode(-1);
        ListNode* tou=tou2;
        head=tou1;
        while(tou1->next){
            if(tou1->next->val>=x){
                tou2->next=tou1->next;
                tou2=tou2->next;
                tou1->next=tou1->next->next;
                tou2->next=NULL;
            }
            else
                tou1=tou1->next;
        }
        tou1->next=tou->next;
        return head->next;
    }
};

algorithm analysis

算法一次遍历链表,时间复杂度O(n)

Last updated