C语言数据结构双向链表

双向链表不仅可以从头向尾查找也可以从尾向头查找。

#include<stdio.h>
#include<stdlib.h>
#include<memory.h>
#ifdef _DEBUG
#include<vld.h>
#endif /*_DEBUG*/


typedef struct _dlist
{
	int data;
	struct _dlist *p_head;
	struct _dlist *p_tail;
}DList,Node;

int dlist_lenght(DList* list);

void insert_head(int data, DList* list)
{
	Node* node = (Node*)malloc(sizeof(Node));
	memcpy(node, list, sizeof(Node));
	list->data = data;
	list->p_head = NULL;
	list->p_tail = node;
	node->p_head = list;
	if (dlist_lenght(list) > 2)
	{
		Node* tmp = node->p_tail;
		tmp->p_head = node;
	}
}

int dlist_lenght(DList* list)
{
	int count = 0;
	Node* tmp = list;
	while (tmp)
	{
		count++;
		tmp = tmp->p_tail;
	}
	return count;
}

void delete_tail(DList* list)
{
	if (list == NULL)
		return;
	if (list->p_head == NULL && list->p_tail == NULL)
	{
		free(list);
		list = NULL;
		return;
	}
	Node* tail = NULL;
	Node* prev = NULL;
	Node* temp = list;
	while (temp->p_tail!=NULL)
	{
		temp = temp->p_tail;
	}
	tail = temp;
	prev = temp->p_head;
	free(tail);
	if(prev!=NULL)
		prev->p_tail = NULL;
}

void dlist_free(DList* list)
{
	if (list == NULL)
		return;
	Node* tmp = NULL;
	while (list)
	{
		tmp = list->p_tail;
		free(list);
		list = tmp;
	}
}

void print(DList* list)
{
	if (list == NULL)
		return;
	Node *tmp = list;
	while (tmp!=NULL)
	{
		printf("Data:%d\np_head:%p\np_tail:%p\n", tmp->data,tmp->p_head,tmp->p_tail);
		tmp = tmp->p_tail;
	}
}

int main()
{
	DList* dlst = (DList*)malloc(sizeof(DList));
	dlst->data = 1001;
	dlst->p_head = NULL;
	dlst->p_tail = NULL;
	printf("lenght of list is %d .\n", dlist_lenght(dlst));
	print(dlst);
	insert_head(101, dlst);
	insert_head(102, dlst);
	insert_head(103, dlst);
	insert_head(104, dlst);
	printf("lenght of list is %d .\n", dlist_lenght(dlst));
	print(dlst);
	printf("---------------------------------\n");
	delete_tail(dlst);
	printf("lenght of list is %d .\n", dlist_lenght(dlst));
	print(dlst);
	printf("---------------------------------\n");
	delete_tail(dlst);
	printf("lenght of list is %d .\n", dlist_lenght(dlst));
	print(dlst);
	printf("---------------------------------\n");
	delete_tail(dlst);
	printf("lenght of list is %d .\n", dlist_lenght(dlst));
	print(dlst);
	dlist_free(dlst);
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Risehuxyc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值