链表反致

#include<iostream>

using namespace std;

struct Mynode
{
    int data;
    struct Mynode *next;

};


class Myopersion
{
public:
    Mynode* Init();//初始化函数
    Mynode* Insert(Mynode* head,int arry[], int len);//插入元素
    void Play(Mynode* myhead);//遍历链表
    Mynode* Fanzhi(Mynode* myhead);//链表反至
    void Clear(Mynode* myhead);//销毁链表
private:
    struct Mynode* head;
};

//创建链表头结点呢
Mynode* Myopersion::Init()
{
    head = new Mynode;
    memset(head, 0, sizeof(Mynode));
    head->next = nullptr;
    return head;
}

//像链表中插入元素
Mynode*  Myopersion::Insert(Mynode* head,int arry[], int len)
{
    Mynode* myhead = head;
    Mynode* tem = nullptr;
    for (int i = 0; i < len; i++)
    {
        tem = new Mynode;
        tem->data = arry[i];

        myhead->next = tem;
        tem->next = nullptr;
        myhead = tem;

    }
    return head;
}


//遍历链表
void Myopersion::Play(Mynode *head)
{
    Mynode* myhead = head->next;
    while (myhead != nullptr)
    {
        cout << myhead->data << "  ";
        myhead = myhead->next;
    }
    cout << endl;

}

//链表进行反转
Mynode* Myopersion::Fanzhi(Mynode* head)
{
    //辅助头结点指针
    Mynode* tem = head;
    //指向需要移动的节点指针
    Mynode* Pcu = nullptr;
    //指向移动节点下一个节点的指针
    Mynode* Pnew = nullptr;
    //指向移动节点的next域指针
    Mynode* Pnext = nullptr;
    //判断链表是否是空链表
    if (head->next == nullptr)
    {
        return nullptr;
    }
    Pcu = tem->next;
    //如果只有一个节点的时候
    if (Pcu->next == nullptr)
    {
        return head;
    }
    Pnew = Pcu;
    while (Pnew != nullptr)
    {
        Pnew = Pcu->next;
        Pcu->next = Pnext;
        Pnext = Pcu;
        Pcu = Pnew;
    }
    head->next = Pnext;
    return head;
}

void Myopersion::Clear(Mynode* myhead)
{
    Mynode* head = nullptr;
    while (myhead != nullptr)
    {
        head = myhead->next;
        delete myhead;
        myhead = head;
    }
}
int main()
{

    int arry[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Myopersion my;
    Mynode* myhead = nullptr;
    myhead = my.Init();
    myhead = my.Insert(myhead, arry, sizeof(arry) / sizeof(*arry));
    my.Play(myhead);

    myhead = my.Fanzhi(myhead);
    cout << "反至以后的链表" << endl;
    my.Play(myhead);

    my.Clear(myhead);
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值