下面为单链表的基本操作:
#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;
}
运行结果如下: