cpp
#include <iostream>
using namespace std;
typedef int ElemType;
// 3. 双链表
typedef struct DNode
{
ElemType data;
struct DNode *prior, *next;
} DNode, *DLinkList;
// 初始化带头结点
bool InitDNodeList(DLinkList &L)
{
L = (DNode *)malloc(sizeof(DNode));
if (L == NULL)
{
return false;
}
L->prior = NULL;
L->next = NULL;
return true;
}
// 在第 i 个位置插入元素 e
bool InsertDNodeList(DLinkList &L, int i, ElemType e)
{
DNode *p = L, *s;
int j = 0;
while (p != NULL && j < i - 1)
{
p = p->next;
j++;
}
if (p == NULL)
{
cout << "插入位置不合法" << endl;
return false;
}
s = (DNode *)malloc(sizeof(DNode));
s->data = e;
// 判断是否在空表中插入
if (p->next == NULL)
{
s->next = NULL;
s->prior = p;
p->next = s;
return true;
}
else
{
s->next = p->next;
s->prior = p;
p->next->prior = s;
p->next = s;
return true;
}
}
// 删除第 i 个元素,并返回元素 e
bool DeleteDNodeList(DLinkList &L, int i, ElemType &e)
{
DNode *p = L, *q;
int j = 0;
while (p != NULL && j < i - 1)
{
p = p->next;
j++;
}
if (p == NULL)
{
cout << "删除位置不合法" << endl;
return false;
}
q = p->next;
e = q->data;
p->next = q->next;
q->next->prior = p;
free(q);
return true;
}
// 遍历双链表
void TraverseDNodeList(DLinkList L)
{
DNode *p = L->next;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main()
{
DLinkList L;
ElemType e;
InitDNodeList(L);
InsertDNodeList(L, 1, 1);
InsertDNodeList(L, 2, 2);
InsertDNodeList(L, 3, 3);
TraverseDNodeList(L);
DeleteDNodeList(L, 2, e);
cout << "删除元素为:" << e << endl;
TraverseDNodeList(L);
return 0;
}