partition-list (list according to the value of the divided two parts)

Disclaimer: This article is written self-study, pointed out that if the error also hope, thank you ^ - ^ https://blog.csdn.net/weixin_43871369/article/details/91350401

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

For example,
Given1->4->3->2->5->2and x = 3,
return1->2->2->4->3->5.

//创建两个链表,遍历原链表,小于x的放在low中,
//大于或者等于x的放在high,最后合并两个链表即可
public:
    ListNode *partition(ListNode *head, int x) {
         if(head==NULL||head->next==NULL) return head;
        ListNode *low=new ListNode(0);
        ListNode *high=new ListNode(0);
        ListNode *p=low,*q=high;
        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=NULL;
        q->next=NULL;
        p->next=high->next;
        return low->next;
    }
};

 

Guess you like

Origin blog.csdn.net/weixin_43871369/article/details/91350401