明天开学了 暑假大概地过完了一遍基本的数据结构 现在也要开始复习 边学其他的东西了 大二开始了 加油 下面的循环双向链表作为链表类的第一个复习
文件"dlist.h"
#include<iostream>
using namespace std;
template<class T>
class DList;
template<class T>
class Node
{
private:
T data; //数据域
Node<T> *prior; //指向直接前驱
Node<T> *next; //指向直接后继
public:
Node()
{
prior=next=NULL;
}
Node(T d)
{
data=d;
prior=next=NULL;
}
friend class DList<T>;
};
template<class T>
class DList
{
private:
Node<T> *head,*tail;
int size; //表长
public:
DList()
{
head=tail=new Node<T>();
head->next=head->prior=head;
size=0;
}
DList(T a[],int n)
{
head=tail=new Node<T>();
size=0;
for(int i=0;i<n;i++)
{
Node<T> *p=create(a[i]);
tail->next=p;
p->prior=tail;
p->next=head;
tail=p;
}
head->prior=tail; //切记要修改头指针的前驱指针
}
Node<T> *create(T d)
{
Node<T> *p=new Node<T>(d);
size++;
return p;
}
void Insert_rear(Node<T> *p) //尾插入
{
tail->next=p;
p->prior=tail;
p->next=head;
tail=p;
head->prior=tail; //修改头指针的前驱指针
}
void Insert_front(Node<T> *p) //头插入
{
head->next->prior=p;
p->next=head->next;
head->next=p;
p->prior=head;
}
int Get_Length()
{
return size;
}
T GetData(Node<T> *p)
{
return p->data;
}
bool Empty()
{
return (tail->next==head);
}
Node<T> *Search(T d) //返回数据在链表中的地址
{
Node<T> *p=head->next;
if(!p)
return NULL;
while(p!=head)
{
if(p->data==d)
return p;
p=p->next;
}
cout<<"查找记录不存在"<<endl;
return NULL;
}
bool Insert(int k,T d) //在第k个结点之后插入数据d
{
if(k<1 || k>size)
return false;
int pos=1;
Node<T> *p=head->next;
Node<T> *q=create(d);
while(pos<k)
{
p=p->next;
pos++;
}
Node<T> *temp=p->next;
q->next=temp;
p->next=q;
temp->prior=q;
q->prior=p;
return true;
}
bool erase(int k,T& d) //删除k号位置的值并返回它的值
{
if(k<1 || k>size)
return false;
int pos=1;
Node<T> *p=head->next;
while(pos<k)
{
p=p->next;
pos++;
}
d=p->data;
Node<T> *p1=p->prior;
Node<T> *n1=p->next;
p1->next=n1;
n1->prior=p1;
if(p==tail)
tail=p1;
delete p;
return true;
}
void Contray_Dul() //逆置
{
Node<T> *p=head->next;
Node<T> *q=head->prior;
T temp;
while(1)
{
temp=p->data;
p->data=q->data;
q->data=temp;
p=p->next;
if(p==q)
return;
q=q->prior;
}
}
void print()
{
Node<T> *p=head->next;
while(p!=head)
{
cout<<p->data<<" ";
p=p->next;
}
}
};
主函数“main.cpp”
#include"dlist.h"
int main()
{
int a[10]={5,4,2,6,8,9,7,1,3,10};
DList<int> dl(a,10);
dl.print();
cout<<endl;
int d=11;
Node<int> *p=dl.create(d);
dl.Insert_front(p);
dl.print();
cout<<endl;
if(dl.erase(3,d))
cout<<"删除的元素值为:"<<d<<endl;
else
cout<<"删除的元素不存在"<<endl;
d=dl.Get_Length();
cout<<"现在表长为:"<<d<<endl;
d=15;
p=dl.create(d);
dl.Insert_rear(p);
dl.print();
cout<<endl;
if(dl.Insert(8,19))
dl.print();
cout<<endl;
p=dl.Search(8);
if(p)
cout<<"8的地址为:"<<p<<endl;
cout<<"____转置链表_____"<<endl;
dl.Contray_Dul();
dl.print();
cout<<endl;
return 0;
}
输出结果
5 4 2 6 8 9 7 1 3 10
11 5 4 2 6 8 9 7 1 3 10
删除的元素值为:4
现在表长为:11
11 5 2 6 8 9 7 1 3 10 15
11 5 2 6 8 9 7 1 19 3 10 15
8的地址为:00380990
____转置链表_____
15 10 3 19 1 7 9 8 6 2 5 11
Press any key to continue