链表的基本操作封装

本文介绍了单链表的基本操作,包括插入、删除、遍历等。通过示例代码展示了这些操作的实现,帮助理解链表数据结构。
摘要由CSDN通过智能技术生成

下面为单链表的基本操作:

#include <iostream>
using namespace std;


struct NODE
{
  int data;
  NODE*pNext;

  NODE(int value)
  {
   data=value;
   pNext=NULL;
  }
};


class List
{
public:
 List()
 {
  m_head=NULL;
  count=0;
 }
 ~List();
 
void insert(NODE*pNode);
//清空整个链表
void destroy(NODE*pNode);
void print();
void reverse();
void reverseRecursive(NODE*pParent,NODE*pChild);//使用递归进行链表的反转
void sort();

//private:
public:
  //链表的头指针
  NODE*m_head;
  //链表节点的数目
  int count;

  void mDestroy();
};

 List::~List()
{
  this->mDestroy();
}

//实现插入的操作
void List::insert(NODE*pNode)
{

 if(this->m_head==NULL)
 {
   this->m_head=pNode;
 
 }
 else
 {
   pNode->pNext=this->m_head;
   this->m_head=pNode;
 
 }

}

//打印链表
void List::print()
{
 NODE*pNode=this->m_head;
 while(pNode!=NULL)
 {
   cout<<pNode->data<<" ";
   pNode=pNode->pNext;
 }
 cout<<endl;

}

void List::mDestroy()
{
 this->destroy(this->m_head);

}

void List::destroy(NODE*pNode)
{
 if(pNode->pNext==NULL)
 {
   cout<<"the delete data is "<<pNode->data<<endl;
   delete pNode;//释放内存
   
 }
 else
 {
   destroy(pNode->pNext);
   cout<<"the delete data is "<<pNode->data<<endl;
   pNode->pNext=NULL;
   delete  pNode;
 }

}

void List::reverse()
{
  if(this->m_head==NULL)
	return ;
  //数目小于2的话不存在反转
  NODE*p1=this->m_head;
  NODE*p2=p1->pNext;
  NODE*p3=p2->pNext;
  if(p2==NULL)
  return ;
  //第一个成为结束的点
  p1->pNext=NULL;
  p2->pNext=p1;
  
  while(p3!=NULL)
  {
     
      p1=p2;
      p2=p3;
	  p3=p3->pNext;
     s p2->pNext=p1;
    
  }

  this->m_head=p2;
}

//使用递归进行链表的反转
void List::reverseRecursive(NODE*pParent,NODE*pChild)
{
 if(pChild==NULL)
 {
   this->m_head=pParent;
 }
 
 else
 {
   reverseRecursive(pParent->pNext,pChild->pNext);
   pChild->pNext=pParent;
 
 }

}


void List::sort()
{ 
 //按照从小到大的顺序排序s

}


int main()
{
  int array[]={1,5,2,6,73,12,98,66,125,45}; 
  int len=sizeof(array)/sizeof(array[0]);
  List list;
  for(int i=0;i<len;i++)
  {
   NODE*pNode=new NODE(array[i]);
   list.insert (pNode);
  }
  list.print();
  
  
  //list.reverse();
  NODE*p_tempHead=list.m_head;
  list.reverseRecursive(list.m_head,list.m_head->pNext);
  p_tempHead->pNext=NULL;
  cout<<"the reverse result is :"<<endl;
  list.print();
  return 0;
}

运行结果如下:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值