Leetcode first _ Partition List

Source: Internet
Author: User

Partition is a quick preparation task. It is used in many other problems, such as finding a number that meets a certain condition.

In an array, you can replace one or more pointers at one end in sequence, which does not guarantee the relative order in the source array. It is different in the linked list. You cannot get the pointer at the end. You can only find the first node that does not meet the partition condition, that is, a large number, and then find a smaller number, move the decimal node to the front, so there is a difference with the array approach. The partition of the linked list only has one pointer to actually move, and the other pointer keeps the insert position.

class Solution {public:    ListNode *partition(ListNode *head, int x) {        if(!head || !head->next)            return head;        ListNode *left = head, *right = head, *pre1 = NULL, *pre2 = NULL;        while(left&&left->val<x){            pre1 = left;            left = left->next;        }        right = left;        while(right){            while(right&&right->val>=x){                pre2 = right;                right = right->next;            }            if(right != left&&right){                pre2->next = right->next;                if(pre1 == NULL){                    right->next = head;                    head = right;                }else{                    right->next = pre1->next;                    pre1->next = right;                }                pre1 = right;                right = pre2->next;            }        }        return head;    }};

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.