数据结构中双向链表头插尾插与遍历节点

#include
#include
#include

//定义节点类型
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_addhead(node_t**, data_t);//函数声明
int dlist_addtail(node_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_addhead(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 = *head;
	if(*head)
		(*head)->prev = pnew;
	*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;
	node_t* p = *head;
	if (*head == NULL)//空链表,创建
	{
		pnew->prev = NULL;
		pnew->next = NULL;
		*head = pnew;
		return 0;
	}
	while (p->next)//不为空链表
	{
		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 i = 0; i < 6; i++)
		dlist_addhead(&head,i + 1);

	dlist_showall(head);

	for (int j = 0; j < 6; j++)
		dlist_addtail(&head, j + 1);

	dlist_showall(head);

	return 0;

}

运行结果:

你可能感兴趣的:(数据结构,链表)