上半年看《数据结构与算法分析 C++描述的》的时候曾写过一个链表,这几天想起来翻了翻VS的工程文件,发现还在,拿出来分享一下。
只支持简单的插入和删除,记得当时在类的构造和析构上费了点周折。
#ifndef LINKLIST_H
#define LINKLIST_H
#include<iostream>
using namespace std;
template<typename object>
class Linklist
{
private:
struct Node;
Node *head;
Node *tail;
int theSize;
public:
Linklist();
~Linklist();
int size(){return theSize;}
void insert(const object &x,object xx);
void erase(const object &x);
void printlist();
};
template<typename object>
struct Linklist<object>::Node
{
object data;
Node *prev;
Node *next;
Node(const object & d=object(),Node *p=NULL,Node *n=NULL):data(d),prev(p),next(n){}
};
template<typename object>
Linklist<object>::Linklist()
{
theSize=0;
head=new Node;
tail=new Node;
//创建空链表,head和tail是逻辑头尾
head->next=tail;
tail->prev=head;
}
template<typename object>
Linklist<object>::~Linklist()
{
//for(Node *p=head;p!=tail;p=p->next)
// delete p;
//delete tail;
Node *p=head;
while(p!=tail)
{
Node *tmp=p->next;
delete p;
p=tmp;
}
delete tail;
}
template<typename object>
void Linklist<object>::insert(const object &x,object xx)
{
Node *p;
for(p=head->next;p!=tail;p=p->next)
{
if (p->data==x)
{
p->next=p->next->prev=new Node(xx,p,p->next);
theSize++;
break;
}
}
if(p==tail) //若找不到,插到尾部
{
p->prev=p->prev->next=new Node(xx,p->prev,p);
theSize++;
cout<<"没找到"<<xx<<",插到尾部!"<<endl;
}
}
template<typename object>
void Linklist<object>::erase(const object &x)
{
Node *p=head->next;
//注意while和if!!!
while(p!=tail)
{
if (p->data==x)
{
Node *tmp=p->next;
p->prev->next=p->next;
p->next->prev=p->prev;
delete p;
//赋值继续查找下一个
p=tmp;
theSize--;
}
else
p=p->next;
}
}
template<typename object>
void Linklist<object>::printlist()
{
cout<<"[";
for(Node *p=head;p!=tail->prev;p=p->next)
cout<<p->next->data<<",";
cout<<"]"<<endl;
}
#endif