C++算法3:链表划分

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
请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/xuan_zizizi/article/details/81557116