数据结构考研复习(双链表)

相较于单链表而言双链表更易于访问前驱结点,其余内容相差并不是很大,我在写这部分内容时基本上也还是套用之前写单链表的代码:

https://www.cnblogs.com/hortz/p/15085147.html

双链表的基本代码如下:

#include<stdio.h>
#include<malloc.h>

typedef struct dnode{
int data;
struct dnode *prior, *next;
}dnode, *dlinklist;

/* -1- 建立双链表(单链表的尾插法)*/
dlinklist insert_list(dlinklist &d){
int x;
d = (dlinklist)malloc(sizeof(dnode));
dnode *temp,*t = d;//t为表尾指针
d->prior = null;
d->next = null;
while(x != 9999){
scanf(“%d”,&x);
temp = (dnode*)malloc(sizeof(dnode));
temp->data = x;
t->next = temp;
temp->prior = t;//可省略
t = temp;
}
return d;
}

/* -2- 获取元素*/
int get_element(dlinklist &d){
dnode *temp = d->next;
while(temp && temp->data!=9999){
printf(“%d “,temp->data);
temp = temp->next;
}
printf(“\n”);
}

/* -3- 插入结点*/
dlinklist insert_element(dlinklist &d,int i,int e){
dnode *previous = d;
int m =0;
while(previous && m < i){
previous= previous->next;
m++;
}
dnode *temp = (dlinklist)malloc(sizeof(dnode));
temp->data = e;

temp->next = previous->next;//1
previous->next->prior = temp;//2
temp->prior = previous;//3
previous->next = temp;//4
//只要逻辑无误可以对上述语句进行删减或者交换顺序

return d;
}

/* -4- 删除结点*/
dlinklist delete_element(dlinklist &d,int i){
dnode *previous = d;
int m = 0;
while(previous && m < (i-1)){
previous= previous->next;
m++;
}
dnode *del_element = previous->next;
previous->next = del_element->next;
del_element->next->prior = previous;
free(del_element);//释放结点空间
}

int main(){
dlinklist d;

printf(“请依次输入数据:\n”);
printf(“===================\n”);
inser
数据结构考研复习(双链表) – HOr7z – 博客园(数据结构考研知识点)插图
t_list(d);
get_element(d);
int flag;
printf(“请进行选择:\n”);
printf(“==1.在指定序列后插入元素==\n”);
printf(“==2.双链表删除元素==\n”);
scanf(“%d”,&flag);
switch(flag){
case(1):
{
printf(“请输入要插入元素的序列:\n”);
int m;
scanf(“%d”,&m);
printf(“请输入要插入的元素值:\n”);
int e;
scanf(“%d”,&e);
insert_element(d,m,e);
get_element(d);
break;
}
case(2):
{
printf(“请输入要删除的元素序列:\n”);
int m;
scanf(“%d”,&m);
delete_element(d,m);
get_element(d);
break;
}

}

return 0;

}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注