#include <iostream>
#include <iomanip>
using
namespace
std;
template
<
class
T>
class
node
{
public
:
T data;
node *next;
};
template
<
class
T>
class
list
{
public
:
list();
void
Create();
bool
Empty()
const
;
void
InsertLast(
const
T e);
void
InsertFirst(
const
T e);
void
DeleteFirst();
void
DeleteLast();
void
Display()
const
;
node<T>* GetNode(
int
i);
void
Reverse();
bool
Find(
const
T e);
~list();
private
:
node<T> *head;
};
template
<
class
T>
list<T>::list()
{
head=
new
node<T>;
head->next=NULL;
}
template
<
class
T>
void
list<T>::Create()
{
node<T> *p,*q;
p=head;
q=
new
node<T>;
cout<<
"请输入值(按'ctrl+z'停止): "
;
while
(cin>>q->data)
{
p->next=q;
p=q;
q=
new
node<T>;
}
p->next=NULL;
}
template
<
class
T>
bool
list<T>::Empty()
const
{
return
(head->next==NULL);
}
template
<
class
T>
void
list<T>::InsertFirst(
const
T e)
{
node<T> *p=
new
node<T>;
p->data=e;
p->next=head->next;
head->next=p;
}
template
<
class
T>
void
list<T>::InsertLast(
const
T e)
{
node<T> *p,*q;
p=head;
q=
new
node<T>;
q->data=e;
while
(p->next)
{
p=p->next;
}
p->next=q;
q->next=NULL;
}
template
<
class
T>
void
list<T>::DeleteFirst()
{
head->next=head->next->next;
}
template
<
class
T>
void
list<T>::DeleteLast()
{
node<T> *p;
p=head;
while
(p->next->next)
p=p->next;
p->next=NULL;
}
template
<
class
T>
void
list<T>::Display()
const
{
node<T> *p;
p=head->next;
while
(p)
{
cout<<p->data<<
" "
;
p=p->next;
}
}
template
<
class
T>
node<T>* list<T>::GetNode(
int
i)
{
int
k=0;
node<T> *p;
p=head;
while
(p && k<i)
{
p=p->next;
++k;
}
return
p;
}
template
<
class
T>
void
list<T>:: Reverse()
{
node<T> *p,*q;
p=head->next;
int
count=0;
while
(p)
{
p=p->next;
count++;
}
int
i,j;
i=1;
j=count;
while
(i<=count/2 && j>=count/2)
{
p=GetNode(i);
q=GetNode(j);
T temp=p->data;
p->data=q->data;
q->data=temp;
++i;
--j;
}
}
template
<
class
T>
bool
list<T>::Find(
const
T e)
{
bool
flag=
false
;
node<T> *p;
p=head->next;
while
(p)
{
if
(p->data==e)
{
flag=
true
;
break
;
}
p=p->next;
}
return
flag;
}
template
<
class
T>
list<T>::~list()
{
node<T> *p;
while
(head)
{
p=head->next;
delete
head;
head=p;
}
}
int
main()
{
list<
int
> ilist;
ilist.Create();
ilist.Display();
cout<<endl;
ilist.InsertFirst(123);
ilist.InsertLast(456);
ilist.Display();
cout<<endl;
if
(ilist.Find(123))
cout<<
"123 在链表中"
<<endl;
else
cout<<
"123 不在链表中"
<<endl;
ilist.DeleteFirst();
ilist.DeleteLast();
ilist.Display();
cout<<endl;
ilist.Reverse();
ilist.Display();
cout<<endl;
system
(
"pause"
);
return
0;
}