双链表在最末端的插入和删除要特别对待。
#include<iostream>
using namespace std;
typedef int ElemType;
//定义双链表节点类型
typedef struct Node
{
ElemType data;
struct Node *next;
struct Node *prior;
}DNode,*DLinkList;
DLinkList DLinkListCreate()
{
DLinkList head,p,q;
head = (DLinkList)malloc(sizeof(DNode));
head->next = NULL;
head->prior = NULL;
p = head;
ElemType elem;
cout<<"输入数据,按ctrl+z结束:"<<endl;
while(cin>>elem)
{
q = (DLinkList)malloc(sizeof(DNode));
q->data = elem;
p->next = q;
q->prior = p;
p = p->next;
}
p->next = NULL;
return head;
}
//双链表长度
int DLinkListLength(DLinkList l)
{
DLinkList p = l->next;
int i = 0;
while(p != NULL)
{
p = p->next;
i++;
}
return i;
}
//双链表的查找,查找元素为x的位置
int DLinkListFind(DLinkList l,ElemType x)
{
DLinkList p = l->next;
int i = 1;
while(p != NULL && p->data != x)
{
i++;
p = p->next;
}
if(p == NULL)
return 0;
else return i;
}
//双链表的插入,在双链表第index个位置插入值为x的元素
void DLinkListInsert(DLinkList &l,int index,ElemType x)
{
if(index < 1 || index > DLinkListLength(l) +1)
{
cout<<"invalid index"<<endl;
return;
}
else
{
int i = 1;
DLinkList p = l,q;
while((i++) < index)
p = p->next;//p指向要插入位置的前一个节点
q = (DLinkList)malloc(sizeof(DNode));
q->data = x;
q->next = p->next;
if(p->next == NULL)//在最后插入是有差别的
{
p->next = q;
q->prior = p;
}
else
{
p->next->prior = q;
p->next = q;
q->prior = p;
}
}
}
//删除指定位置index处的数据
void DLinkListDelIndex(DLinkList &l,int index)
{
if(index < 1 || index > DLinkListLength(l))
{
cout<<"invalid index"<<endl;
return;
}
else
{
DLinkList p = l,q;
int i = 1;
while(i < index)
{
p = p->next;
i++;
}
if(p->next->next == NULL)//如果删除最后一个元素,特殊处理,最后元素的next为NULL,没有prior。
{
q = p->next;
p->next = NULL;
free(q);
}
else
{
q = p->next;
p->next = q->next;
p->next->prior = p;
free(q);
}
}
}
//删除所有值为x的元素
void DLinkListDelElem(DLinkList &l,ElemType x)
{
DLinkList p = l->next,q;
while(p != NULL)
{
if(p->data == x)
{
q = p;
if(p->next == NULL)
{
p->prior->next = NULL;
}
else
{
p->prior->next = p->next;
p->next->prior = p->prior;
}
p = p->next;
free(q);
}
else
p = p->next;
}
}
void DLinkListPrint(DLinkList l)
{
DLinkList p = l->next;
int i = 0;
while(p != NULL)
{
cout<<p->data<<"\t";
i++;
if(i%5 == 0)
cout<<endl;
p = p->next;
}
}
//逆序打印
void DLinkListPrintRev(DLinkList l)
{
DLinkList p = l;
while(p->next != NULL)
p = p->next;
int i = 0;
while(p != l)
{
cout<<p->data<<"\t";
i++;
if(i%5 == 0)
cout<<endl;
p = p->prior;
}
}
int main()
{
DLinkList l;
l = DLinkListCreate();
DLinkListDelElem(l,3);
DLinkListInsert(l,4,5);
DLinkListPrint(l);
return 1;
}