partition-list(链表根据值分割两部分)

版权声明:本文为自学而写,如有错误还望指出,谢谢^-^ https://blog.csdn.net/weixin_43871369/article/details/91350401

题目描述

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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43871369/article/details/91350401