#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//定义节点类型
typedef int data_t;
typedef struct node
{
data_t data;//以整型数据为例
struct node* prev;//指向struct node 点的指针
struct node* next;//指向struct node 点的指针
}node_t;
int dlist_create(node_t**, data_t);//函数声明
int dlist_addtail(node_t**, data_t);//函数声明
int dlist_insert(node_t**, data_t, data_t);//函数声明
void dlist_showall(node_t*);//函数声明
/***
创建双向列表
head:接收头指针地址的指针变量
data:待存储的数据
return -1:链表创建失败
return 0:链表创建成功
***/
int dlist_create(node_t** head, data_t data)
{
node_t* pnew = (node_t*)malloc(sizeof(node_t));
if (pnew == NULL)
return -1;
pnew->data = data;
pnew->prev = NULL;
pnew->next = NULL;
*head = pnew;
return 0;
}
/***
双向列表尾插节点
head:接收头指针地址的指针变量
data:待插入的数据
return -1:链表创建失败
return 0:链表创建成功
***/
int dlist_addtail(node_t** head, data_t data)
{
node_t* pnew = (node_t*)malloc(sizeof(node_t));
if (pnew == NULL)
return -1;
pnew->data = data;
pnew->next = NULL;
if (*head == NULL)//空链表,创建
{
pnew->prev = NULL;
*head = pnew;
return 0;
}
node_t* p = *head;
while (p->next)//不为空链表
{
p = p->next;
}
p->next = pnew;
pnew->prev = p;
return 0;
}
/***
双向列表中间插节点
head:接收头指针地址的指针变量
pos:插入位置的数据值
new_data:待插入的新数据
return -1:链表创建失败
return 0:链表创建成功
***/
int dlist_insert(node_t** head, data_t pos, data_t new_data)
{
// 创建新节点
node_t* pnew = (node_t*)malloc(sizeof(node_t));
if (pnew == NULL)
return -1;
pnew->data = new_data;
// 空链表处理
if (*head == NULL)
{
pnew->prev = NULL;
pnew->next = NULL;
*head = pnew;
return 0;
}
node_t* p = *head;
// 如果要插入的位置是头节点
if (p->data == pos)
{
pnew->prev = NULL;
pnew->next = p;
p->prev = pnew;
*head = pnew;
return 0;
}
// 查找插入位置
while (p != NULL)
{
if (p->data == pos)
{
// 在找到的节点前插入新节点
pnew->next = p;
pnew->prev = p->prev;
p->prev->next = pnew;
p->prev = pnew;
return 0;
}
p = p->next;
}
// 如果没找到指定位置,则插入到尾部
p = *head;
while (p->next != NULL)
{
p = p->next;
}
p->next = pnew;
pnew->prev = p;
pnew->next = NULL;
return 0;
}
//遍历双向链表
void dlist_showall(node_t* head)
{
node_t* p = head;
while (p)
{
printf("%3d", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
node_t* head = NULL;
dlist_create(&head, 1024);
for (int j = 0; j < 6; j++)
dlist_addtail(&head, j + 1);
printf("初始链表内容:\n");
dlist_showall(head);
while (1)
{
printf("\n请输入要插入处节点数据(-1退出):");
data_t pos;
scanf_s("%d", &pos);
if (pos == -1)
break;
printf("请输入要插入的新数据:");
data_t new_data;
scanf_s("%d", &new_data);
if (dlist_insert(&head, pos, new_data) == 0)
{
printf("插入后的链表内容:\n");
dlist_showall(head);
}
else
{
printf("插入失败!\n");
}
}
// 释放链表内存
node_t* current = head;
while (current != NULL)
{
node_t* temp = current;
current = current->next;
free(temp);
}
return 0;
}
运行结果: