带有头节点的单链表的逆置

本文介绍了一种使用模板类实现单链表逆置的方法,包括初始化、展示链表内容、插入元素及逆置链表操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<string>
using namespace std;

/******************这是带有头节点的单链表的逆置××××××××××××××*/
template <class Type>
struct P
{
    Type data;
    P<Type> *next;
};

template <class Type>
class pc
{
    public:
    P<Type> *head;
    P<Type> *tail;
    public:
        void init();
        void show();
        void insert_first();

        void nizhi();
        void destory();
};

template <class Type>
void pc<Type>::init()
{
    head=new P<Type>;
    tail=head;
    cout<<this->head->data<<endl;
    head->next=NULL;
}

template <class Type>
void pc<Type>::show()
{
    if(head==NULL)
    {
        cout<<"链表为空"<<endl;
    }
    else
    {
        P<Type> *link=head->next;
        cout<<"数据为: ";
        while(link)
        {
            cout<<link->data<<" ";
            link=link->next;
        }
        cout<<endl;
    }
}

template <class Type>
void pc<Type>::insert_first()
{
    cout<<"请输入数据"<<endl;
    P<Type> *link=new P<Type>;
    cin>>link->data;
    if(head->next==NULL)
    {
        head->next=link;
        link->next=NULL;
        tail=link;
    }
    else
    {
        head->next=link;
        link->next=tail;
        tail=link;
    }

    show();

}

template <class Type>
void pc<Type>::nizhi()
{
   P<Type> *p1,*p2,*p3;
   p1=head;
   p2=p1->next;
   while(p2)
   {
       p3=p2->next;
       p2->next=p1;
       p1=p2;
       p2=p3;
   }
   head->next=NULL;
   p3=p1;
   cout<<"逆置之后的数据" ;
   while(p1!=head)
   {
      cout<<p1->data<<" ";
      p1=p1->next;
   }
   cout<<endl;
  // return p3;

}

template <class Type>
void pc<Type>::destory()
{
    P<Type> *p1=head;
    while(head)
    {
      head=head->next;
      delete p1;
      p1=head;
    }
    p1=head=NULL;
    if(p1!=NULL||head!=NULL)
    {
        cout<<"内存有问题"<<endl;

    }
}


//template <class Type>
int main()
{
    pc<string> code;
    code.init();
    code.insert_first();
    code.insert_first();
    code.insert_first();
    code.nizhi();
    //code.destory();
//	code.show();
    return 0;
}




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值