#include <iostream>
#include <stdlib.h>
template <class T>
struct Node{ //结点类型
T data;
Node *next; //前驱结点
Node *prev; //后继结点
};
template <class T>
class lnkList{ //链表类型
Node<T> *head,*tail;
public:
lnkList(){ //初始化链表
head = tail =new Node<T>;
head->next=NULL;
}
~lnkList(){ //析构函数,删去链表
Node<T> *tmp;
while(head!=NULL){
tmp=head;
head=head->next;
delete tmp;
}
}
bool Insert(const int n,T value);
bool Delete(const int n,T &value);
bool TailAppend(const T value);
bool headAppend(const T value);
bool GetValue(const int n,T &value);
void Print();
};
template <class T>
bool lnkList<T>::headAppend(const T value){ //头插法
Node<T> *p=new Node<T>;
p->data=value;
p->next=head->next;
p->prev=head;
head->next->prev=p;
head->next=p;
return true;
}
template <class T>
bool lnkList<T>::TailAppend(const T value){ //尾插法
Node<T> *p=tail;
Node<T> *q=new Node<T>;
q->data=value;
q->prev=q;
q->next=NULL;
p->next=q;
tail=q;
return true;
}
template <class T>
void lnkList<T>::Print(){ //打印输出链表
Node<T> *p=head->next;
while(p!=NULL){
std::cout<<p->data<<std::endl;
p=p->next;
}
}
template <class T>
bool lnkList<T>::Insert(const int n,T value){ //在链表第n个位置插入元素
Node<T> *q=head;
int count=1;
while(q&&count<n){
q=q->next;
++count;
}
if(!q||count>n){
return false;
}
Node<T> *p=new Node<T>;
p->data=value;
p->prev=q;
p->next=q->next;
q->next->prev=p;
q->next=p;
return true;
}
template <class T>
bool lnkList<T>::Delete(const int n,T &value){ //删除链表的第n个位置元素
Node<T> *q=head;
int count=1;
while(q&&count<n){
q=q->next;
++count;
}
Node<T> *p=q->next;
q->next=p->next;
p->next->prev=q;
value=p->data;
delete p;
return true;
}
template <class T>
bool lnkList<T>::GetValue(const int n,T &value){ //得到链表的第n个元素
Node<T> *q=head;
int count=1;
while(q&&count<n){
q=q->next;
++count;
}
if(n<1||!q){
return false;
}
value=q->next->data;
return true;
}
//测试代码
//
int main(int argc, char* argv[])
{
double m;
lnkList<double> l;
l.TailAppend(2);
l.TailAppend(3);
l.TailAppend(4);
l.TailAppend(5);
l.headAppend(1);
l.headAppend(0);
l.Insert(3,1.5);
l.GetValue(3,m);
l.Print();
return 0;
}
//
//在VS2008上测试通过