#include<iostream>
#include<stdlib.h>
using namespace std;
template<class T>
struct LinkNode
{
T data;
LinkNode<T> * link;
LinkNode(LinkNode<T>*ptr=NULL){link=ptr;}
LinkNode(const T&item,LinkNode<T>*ptr=NULL)
{data=item;link=ptr;}
};
template <class T>
class List //单链表类定义
{ protected:
LinkNode<T> *h; //表头指针
public:
List() { h = new LinkNode<T>; } //构造函数
List(const T& x) { h = new LinkNode<T>(x); }
List( List<T>& L);
~List(){ makeEmpty(); }
void makeEmpty();
int Length() const;
LinkNode<T> *Locate(int i);
void input(T endTag);
void output();
void Nizhuan();
};
template <class T>
void List<T>::makeEmpty() {
LinkNode<T> *q;
while (h->link != NULL) {
q = h->link; //保存被删结点
h->link = q->link; //从链上摘下该结点
delete q; //删除
}
}
template <class T>
int List<T> :: Length ( ) const {
ListNode<T> *p = h->link;
int count = 0;
while ( p != NULL ) //逐个结点检测
{ p = p->link; count++; }
return count;
}
template <class T>
LinkNode<T> *List<T>::Locate ( int i )
{//函数返回表中第 i 个元素的地址。若i < 0或 i 超
//出表中结点个数,则返回NULL。
if (i < 0) return NULL; //i不合理
LinkNode<T> *current = h; int k = 0;
while ( current != NULL && k < i )
{ current = current->link; k++; }
return current; //返回第 i 号结点地址或NULL
}
template <class T>
void List<T> ::input ( T endTag )
{ LinkNode<T> *newNode, *last;
T val;
makeEmpty(); cin>>val; last = h;
while (val != endTag)
{ newNode = new LinkNode<T>(val);
if ( newNode == NULL )
{ cerr<<"内存分配错误!"<<endl; exit(1);}
last->link = newNode; //插在表尾
last = newNode;
cin >> val;
}
}
template < class T >
void List< T >::output()
{ LinkNode< T > *current = h->link;
while ( current !=NULL )
{ cout<<current->data<<endl;
current = current->link;
}
}
template <class T>
void List<T>:: Nizhuan()
{
LinkNode<T> *p, *r;
p=h->link;
h->link=NULL;
while (p)
{
r=p->link;
p->link=h->link;
h->link=p;
p=r;
}
};
void main ()
{
List<int> LA;
cout<<"请输入单链表LA,以数字0为结尾:"<<endl;
LA.input(0);
LA.Nizhuan();
cout<<"逆转后的LA是:"<<endl;
LA.output();
}