双链表
双链表的结构:
在逻辑相邻的两个物理元素在物理位置上不相邻
双链表代码实现
- 头插法
- 尾插法
- 删除第i个结点
- 按序号查找结点值
- 按值查找结点值
- 新结点插入第i个位置
- 链表的打印
- 代码
#include<stdio.h>
#include<stdlib.h>
typedef int Elemtype;
typedef struct Dnode {
Elemtype data; // 值域
struct Dnode* prior; // 前继指针
struct Dnode* next; // 后继指针
} Dnode, * Dlinklist;
// 头插法
Dlinklist Head_InsertList(Dlinklist& L)
{
int x;
L = (Dlinklist)malloc(sizeof(Dnode)); // 申请内存空间,如果第一次插入数据元素,这里可以理解为创建一个头结点
Dnode* s;
L->prior = NULL; // 初始化双链表
L->next = NULL;
scanf("%d", &x);
while (x != 9999)
{
s = (Dnode*)malloc(sizeof(Dnode));
s->data = x;
s->next = L->next;
if (L->next != NULL)
L->next->prior = s;
s->prior = L;
L->next = s;
scanf("%d", &x);
}
return L;
}
// 尾插法
Dlinklist Tail_InsertList(Dlinklist& L)
{
int x;
L = (Dlinklist)malloc(sizeof(Dnode));
L->prior = NULL;
Dnode* s= L;
Dnode* r = L;
scanf("%d", &x);
while (x != 9999)
{
s = (Dnode*)malloc(sizeof(Dnode));
s->data = x;
s->prior = r;
r->next = s;
r = s;
scanf("%d", &x);
}
s->next = NULL;
return L;
}
// 按序号查找第i个结点
Dlinklist Sequence_SearchList(Dlinklist L, int i)
{
int loc = 1;
if (i == 0)
return L;
if (i < 1)
return NULL;
Dlinklist p = L->next; // 让指针p指向第一个结点
while (p && (loc < i)) //
{
p = p->next;
loc++;
}
return p;
}
// 按值查找
int Value_SearchList(Dlinklist L, Elemtype e)
{
int loc=1;
Dlinklist p = L->next;
while (p != NULL)
{
if (p->data == e)
return loc;
else
{
p = p->next;
loc++;
}
}
return 0;
}
// 删除第i个结点
bool DeleteLIst(Dlinklist& L, int i)
{
if (i == 0)
return false;
if (i < 1)
return false;
Dlinklist p = Sequence_SearchList(L, i - 1);
if (p == NULL)
return false;
Dlinklist q = p->next;
if (q == NULL)
return false;
p->next = q->next;
if (q->next == NULL)
return false;
q->next->prior = p;
free(q); // 释放q结点空间
q = NULL; // 避免出现野指针
return true;
}
// 在第i个结点插入元素
bool Middle_InsertList(Dlinklist& L, int i, Elemtype e)
{
if (i == 0)
return false;
if (i < 1)
return false;
Dlinklist p = Sequence_SearchList(L, i - 1);
if (p == NULL)
return false;
Dnode* s = (Dlinklist)malloc(sizeof(Dnode));
s->data = e;
s->next = p->next;
p->next->prior = s;
s->prior = p;
p->next = s;
return true;
}
// 链表打印
void PrintList(Dlinklist L)
{
L = L->next;
while (L != NULL)
{
printf("%d ", L->data);
L = L->next;
}
printf("\n");
}
int main(void)
{
Dlinklist L;
Dlinklist search;
int loc;
bool flag;
// 头插法
//Head_InsertList(L);
//PrintList(L);
// 尾插法
Tail_InsertList(L);
PrintList(L);
// 按序号查找第i个结点
search = Sequence_SearchList(L, 3);
if (search)
printf("查找成功,第%d个结点上的值为%d\n", 3, search->data);
else
printf("查找失败\n");
// 按值查找
loc = Value_SearchList(L, 7);
if (loc)
printf("查找成功,值%d位于第%d个结点上\n", 7, loc);
else
printf("查找失败\n");
// 删除第i个结点
flag = DeleteLIst(L, 3);
if (flag)
{
printf("删除成功!\n");
PrintList(L);
}
else
printf("删除失败\n");
// 在第i个结点插入元素
flag = Middle_InsertList(L, 3, 20);
if (flag)
{
printf("插入成功\n");
PrintList(L);
}
else
printf("插入失败\n");
return 0;
}