一、头文件的使用
#include<stdlib.h>
#include<stdio.h>
#define Type int
二、双链表节点的初始化
1、构建节点
struct node
{
Type data;
struct node* prev;
struct node* next;
};
2、节点初始化函数的编写
struct node* list_init(Type value)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->prev = NULL;
temp->next = NULL;
temp->data = value;
return temp;
}
三、双链表头节点和尾节点的构建
1、构建头、尾节点
struct linklist
{
struct node* head;
struct node* tail;
int size;
};
2、头、尾节点初始化函数
struct linklist* list_creat()
{
struct linklist* link = (struct linklist*)malloc(sizeof(struct linklist));
link->head = link->tail = NULL;
link->size = 0;
return link;
}
四、构建双链表函数(尾插)
void list_add(struct linklist* link, Type value)
{
if (link->head == NULL)
{
link->head = list_init(value);
link->tail = link->head;
link->size++;
}
else
{
struct node* temp = list_init(value);
link->tail->next = temp;
temp->prev = link->tail;
link->tail = temp;
link->size++;
}
}
五、双链表数据的插入
void list_insert(struct linklist* link, Type value, int index)
{
if (1 == index)
{
struct node* newnode = list_init(value);
newnode->next = link->head->next;
newnode->data = link->head->next->data;
newnode->prev = link->head;
link->head->data = value;
link->head->next = newnode;
}
struct node* temp = link->head;
for (int i = 1; i < index - 1; i++)
{
temp = temp->next;
}
struct node* newnode = list_init(value);
newnode->next = temp->next;
temp->next->prev = newnode;
temp->next = newnode;
newnode->prev = temp;
}
六、双链表节点的删除(删除头节点)
void list_head_delete(struct linklist* link)
{
if (link->size == 1)
{
free(link->tail);
link->tail = link->head = NULL;
}
else
{
link->head = link->head->next;
free(link->head->prev);
link->head->prev = NULL;
}
}
七、双链表节点的删除(删除尾节点)
void list_end_delete(struct linklist* link)
{
if (link->size == 1)
{
free(link->tail);
link->tail = link->head = NULL;
}
else
{
link->tail = link->tail->prev;
free(link->tail->next);
link->tail->next = NULL;
}
}
八、双链表的输出
void list_out(struct linklist* link)
{
struct node* temp = link->head;
while (temp != NULL)
{
printf("%d\t", temp->data);
temp = temp->next;
}
printf("\n");
}
九、双链表的销毁
void list_destory(struct linklist* link)
{
struct node* temp = link->head;
for (; temp != NULL; )
{
struct node* n = temp;
temp = temp->next;
free(n);
}
}
十、双链表函数的调用
int main()
{
Type value;
struct linklist* p1=list_creat();
printf("请输入要输入的数据:\n");
for(int i=0;i<6;i++)
{
scanf_s("%d", &value);
list_add(p1, value);
}
printf("要输出的数据为:\n");
list_out(p1);
list_insert(p1, 50, 3);
printf("要输出的数据为:\n");
list_out(p1);
list_end_delete(p1);
printf("要输出的数据为:\n");
list_out(p1);
list_destory(p1);
system("pause");
return 0;
}