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.

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


解题思路:

可以借助一个链表实现,将小于x的结点都插入该链表,这样就有了两个链表。这时候,我们只要将小的那个链表放到前面与另一个链表拼接在一起即可。

代码实现:

class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        //创建两个链表,将小于x的结点插入一个链表,剩下的插入另一个链表,在进行拼接即可
        if(head == NULL)
            return NULL;
        ListNode* cur = head;
        ListNode* min = NULL;
        ListNode* mintail = NULL;
        ListNode* max = NULL;
        ListNode* maxtail = NULL;
        while(cur)
        {
            if(cur->val < x)
            {
                if(min)
                {
                    mintail->next = cur;
                }
                else
                {
                    min = cur;
                }
                mintail = cur;
            }
            else
            {
                if(max)
                {
                    maxtail->next = cur;
                }
                else
                {
                    max = cur;
                }
                maxtail = cur;
            }
            cur = cur->next;
        }
        if(mintail)
            mintail->next = NULL;
        if(maxtail)
            maxtail->next = NULL;
        //将两个链表连在一起,这里要注意,如果其中一个链表为空的情况
        if(mintail)
        {
            mintail->next = max;
            return min;
        }
        return max;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_40417029/article/details/80975387