双向链表的基本操作:
建立、插入、查找、删除
与单链表相似,但单链表只需操作next,双链表需对prior和next操作。
1、创建
typedef struct DuLNode
{
ElemType data;
struct DuLNode* prior;
struct DuLNode* next;
}DuLNode, * DuLinkList;
2、添加数据元素
void CreateList_R(DuLinkList& L, int n)//后插法插入数据元素
{
DuLinkList r, p;
L = new DuLNode;
L->next = NULL;//先建立一个带头结点的空链表
r = L;
for (int i = 0; i < n; i++)
{
p = new DuLNode;
cin >> p->data;
p->next = NULL;
r->next = p;
p->prior = r;
r = p;
}
}
3、查找位置
int LocateElem(DuLinkList L, int n, ElemType e)//按值查找
{
DuLinkList p;
int j = 1;
p = L->next;
while (p && p->data != e)
{
p = p->next;
j += 1;
}
if (j > n)
{
return ERROR;
}
return j;
}
4、插入
void LInsert(DuLinkList& L, int i, ElemType a)//在第i个位置前插入元素a
{
DuLinkList p, s;
p = GetElem(L, i);
if (!p)
cout << "ERROR!" << endl;
s = new DuLNode;
s->data = a;
s->prior = p->prior;
p->prior->next = s;
s->next = p;
p->prior = s;
cout << "OK" << endl;
}
5、删除
Status LDelete(DuLinkList& L, int i)//删除
{
DuLinkList p;
if (!(p = GetElem(L, i)))
return ERROR;
p->prior->next = p->next;
p->next->prior = p->prior;
delete p;
return OK;
}
完整代码(Visual Studio 2019):
#include<iostream>
#define ERROR -1
#define OK 1
using namespace std;
typedef int Status;
typedef int ElemType;
typedef struct DuLNode
{
ElemType data;
struct DuLNode* prior;
struct DuLNode* next;
}DuLNode, * DuLinkList;
void CreateList_R(DuLinkList& L, int n)//后插法插入数据元素
{
DuLinkList r, p;
L = new DuLNode;
L->next = NULL;//先建立一个带头结点的空链表
r = L;
for (int i = 0; i < n; i++)
{
p = new DuLNode;
cin >> p->data;
p->next = NULL;
r->next = p;
p->prior = r;
r = p;
}
}
int LocateElem(DuLinkList L, int n, ElemType e)//按值查找
{
DuLinkList p;
int j = 1;
p = L->next;
while (p && p->data != e)
{
p = p->next;
j += 1;
}
if (j > n)
{
return ERROR;
}
return j;
}
DuLinkList GetElem(DuLinkList& L, int i)//获取位置指针
{
DuLinkList p;
p = L->next;
int j = 1;
while (p && j < i)
{
p = p->next;
++j;
}
if (!p || j > i)
{
return NULL;
}
return p;
}
void LInsert(DuLinkList& L, int i, ElemType a)//在第i个位置前插入元素a
{
DuLinkList p, s;
p = GetElem(L, i);
if (!p)
cout << "ERROR!" << endl;
s = new DuLNode;
s->data = a;
s->prior = p->prior;
p->prior->next = s;
s->next = p;
p->prior = s;
cout << "OK" << endl;
}
Status LDelete(DuLinkList& L, int i)//删除
{
DuLinkList p;
if (!(p = GetElem(L, i)))
return ERROR;
p->prior->next = p->next;
p->next->prior = p->prior;
delete p;
return OK;
}
void display(DuLinkList& L)//显示
{
DuLinkList p;
p = L->next;
cout << "链表为:" << endl;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main()
{
DuLinkList L;
int n, i, e = 0, data;
cout << "输入链表长度:" << endl;//赋值
cin >> n;
cout << "请输入数据:" << endl;
CreateList_R(L, n);
cout << "链表长度为:" << endl;
cout << n << endl;
display(L);
cout << "输入要查找的值:" << endl;
cin >> i;
cout << "该值的位置:" << endl;
cout << LocateElem(L, n, i) << endl;
cout << "输入插入的位置和数据:" << endl;
cin >> i;
cin >> data;
LInsert(L, i, data);
display(L);
cout << "输入要删除的位置:" << endl;
cin >> i;
LDelete(L, i);
display(L);
return 0;
}
运行截图: