# 双向链表基础

### 定义双向链表

typedef struct DNode {
ElemType data;  //数据域
struct DNode *pred, *succ;  //前驱和后继域


### 双向链表的尾插法初始化：

//尾插法
void InitList(DLinkList &L, int n)
{
DNode *p, *q;
L = (DNode*)malloc(sizeof(DNode));
if(!L) exit(0);
L->succ = L->pred = NULL;
p = L;
for(int i = 1; i <= n; ++i) {
q = (DNode*)malloc(sizeof(DNode));
q->data = i;
if(!q) exit(0);
q->succ = NULL;
p->succ = q;
q->pred = p;
p = q;
}
}


### 双向链表中的插入操作

//在第i个位置之后插入新的元素
bool InsertDNode(DLinkList &L, int i, int e)
{
int j = 1;
DNode *p, *q, *s;
p = L;
while(p && j < i) {
p = p->succ;
j++;
}
if(!p || j > i) return false;
s = (DNode*)malloc(sizeof(DNode));
s->data = e;
s->pred = p;  //第一步
s->succ = p->succ; //第二步
p->succ->pred = s; //第三步
p->succ = s;  //第四步
}


### 双向链表的删除操作

bool DeleteDNode(DLinkList &L, int i, int &e)
{
int j = 1;
DNode *p, *q, *s;
p = L;
while(p && j <= i) {  //找到结点i所在位置
p = p->succ;
j++;
}
if(!p || j > i + 1) return false;
p->pred->succ = p->succ;
p->succ->pred = p->pred;
free(p);
return true;
}


### 总结

posted @ 2018-12-29 12:22  schrodingercatss  阅读(...)  评论(...编辑  收藏