Partition List

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,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

分析:
题意:给定一个单链表和一个x,把链表中小于x的放到前面,大于等于x的放到后面,每部分元素的原始相对位置不变。

思路:遍历一遍链表,把小于x的都挂到head1后,把大于等于x的都放到head2后,最后再把大于等于的链表挂到小于链表的后面就可以了。

#include <iostream>

using namespace std;

class LNode
{
public:
    int val;
    LNode *next;
    LNode(int x):val(x),next(nullptr){ }
};

class Solution
{
public:
    LNode* partitionList(LNode* L,int x)
    {
        LNode left_head(-1) ;     //头节点
        LNode right_head(-1) ;    //头节点

        auto left = &left_head;
        auto right = &right_head;

        LNode *cur = L->next;   //用来遍历链表的

        while (cur != nullptr)
        {
            if (cur->val < x)
            {
                left->next = cur;
                left = cur;

            }
            else
            {
                right->next = cur;
                right = cur;

            }

            cur = cur->next;
        }

        left->next = right_head.next;   //连接起来

        right->next = nullptr;

        return left_head.next;
    }
};

int main()
{
    LNode *L = new LNode(-1);   //创建头节点
    LNode *p = L;
    int value;
    //尾插法创建一个链表,输入1->4->3->2->5->2
    for (int i = 0; i < 6 ; ++i)
    {
        cin>>value;
        p->next = new LNode(value);
        p = p->next;
        cout<<p->val;
        if (i < 5)
            cout<<"->";

    }
    cout<<endl;

    int x = 3;
    Solution solution;
    LNode *q = solution.partitionList(L,x);
    LNode *ptr;
    //输出链表
    while (q != nullptr)
    {
        ptr = q;
        cout<<q->val;
        if (q->next != nullptr)
            cout<<"->";
        q = q->next;

        delete ptr;//释放分配的内存
    }

    cout<<endl;

    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值