C++算法3:链表划分

18 篇文章 1 订阅
15 篇文章 0 订阅

1.给定一个链表和一个值X,将链表划分为两部分,使得划分后小于X的节点在前,大于等于X的节点在后。这两部分要保持原来链表中的顺序。
2.程序:

# include <iostream> 
using namespace std;

//定义节点结构
typedef struct snode
{
    int data;
    snode *pnext;
    snode(int value)
        :data(value), pnext(NULL)
    {}
}Node;

//声明函数
void OutLink(Node *pHead);
void Destroy(Node *P);
void PartitionLink(Node *Head, int number);

//输出链表
void OutLink(Node *pHead)
{
    //注意判断指针是否为空
    if (pHead == NULL)
    {
        cout << "链表为空";
    }
    Node *pCur = pHead->pnext;
    while (pCur != NULL)
    {
        cout << "->" << pCur->data;
        pCur = pCur->pnext;
    }
    cout << endl;
}

//删除指针
void Destroy(Node *P)
{
    Node *next;
    if (P != NULL)
    {
        next = P->pnext;
        delete P;
        P = next;
    }
}

//划分大小值
void PartitionLink(Node *Head, int number)
{
    Node *pSmall = new Node(0);
    Node *pBig = new Node(0);
    Node *Next = Head->pnext;
    Node *small = pSmall;
    Node *big = pBig;
    while (Next)
    {
        if (Next->data < number)
        {
            small->pnext = Next;
            small = small->pnext;
        }
        else
        {
            big->pnext = Next;
            big = big->pnext;
        }
        Next = Next->pnext;
    }
    small->pnext = pBig->pnext;
    big->pnext = NULL;
    Head->pnext = pSmall->pnext;
    Destroy(pSmall);
    Destroy(pBig);
}

//主函数
int main()
{
    Node *Head = new Node(0);
    Node *Next = Head;
    for (int i = 0; i < 10; i++)
    {
        Next->pnext = new Node(rand() % 100);
        Next = Next->pnext;
    }
    cout << "划分之前" << endl;
    OutLink(Head);
    PartitionLink(Head, 50);
    cout << "划分之后" << endl;
    OutLink(Head);
    Destroy(Head);

    return 0;
}

3.结果:

划分之前
->41->67->34->0->69->24->78->58->62->64
划分之后
->41->34->0->24->67->69->78->58->62->64
请按任意键继续. . .
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值