其基本思想即利用三个辅助指针同时后移解决,很多链表问题都需要考虑到辅助指针
#include <iostream>
#include <assert.h>
using namespace std;
template<typename T>
class List
{
public:
List()
{
pHead=NULL;
}
~List()
{
if(pHead==NULL)
{
return;
}
Node* p;
while(pHead!=NULL)
{
p=pHead;
pHead=pHead->pNext;
delete p;
}
}
bool insertElemt(const T & t)
{
Node* node=new Node;
assert(node!=NULL);
node->t=t;
if(pHead!=NULL)
{
node->pNext=pHead;
pHead=node;
}
else
{
pHead=node;
}
return true;
}
bool deleteElemt(const T & t)
{
Node* p,*q;
p=q=pHead;
while(p->t!=t&&p!=NULL)
{
p=p->pNext;
if(q->pNext!=p)
{
q=q->pNext;
}
}
q->pNext=p->pNext;
delete p;
return true;
}
void print()
{
Node* p=pHead;
while(p!=NULL)
{
cout<<p->t<<" ";
p=p->pNext;
}
cout<<endl;
}
void reverse();
private:
struct Node
{
T t;
Node* pNext;
Node():t(0),pNext(NULL){}
};
Node* pHead;
};
template<typename T>
void List<T>::reverse()
{
Node* p,*q,*r;
p=NULL;
q=pHead;
r=q->pNext;
do
{
q->pNext=p;
p=q;
q=r;
r=r->pNext;
} while (r!=NULL);
q->pNext=p;
pHead=q;
}
int main()
{
List<int> _list;
_list.insertElemt(1);
_list.insertElemt(2);
_list.insertElemt(8);
_list.insertElemt(3);
_list.insertElemt(5);
//_list.deleteElemt(3);
_list.reverse();
_list.print();
getchar();
}