双循环链表(纯C语言实现)

双循环链表(带头结点,头节点数据域为节点数)

#include <stdio.h>
#include <stdlib.h>//开辟空间需要包含此头文件
//双循环链表节点结构体,包含数据域、pre指针域、next指针域
typedef struct Node {
	int data;
	struct Node* pre;
	struct Node* next;
}Node;
//初始化双循环链表,即初始化其头节点并返回其头节点结构体指针
Node* initLoopDoubleLinkList() {
	Node* list = (Node*)malloc(sizeof(Node));
	list->data = 0;
	list->pre = list;
	list->next = list;
	return list;
}
//头插法函数
void headPush(Node* list, int data) {
	Node* n = (Node*)malloc(sizeof(Node));
	n->data = data;
	n->pre = list;
	n->next = list->next;
	if (list->next != list) {
		list->next->pre = n;
	}
	else {
		list->pre = n;
	}
	list->next = n;
	list->data++;
}
//尾插法函数
void tailPush(Node* list, int data) {
	Node* n = (Node*)malloc(sizeof(Node));
	list->pre->next = n;
	n->pre = list->pre;
	n->data = data;
	n->next = list;
	list->pre = n;
	list->data++;
}
//删除双循环链表中指定数值的节点函数
int delete(Node* list, int data) {
	Node* temp = list->next;
	while (temp != list) {
		if (temp->data == data) {
			temp->pre->next = temp->next;
			if (temp->next != list) {
				temp->next->pre = temp->pre;
			}
			else {
				list->pre = list;
			}
			free(temp);
			list->data--;
			return 1;
		}
		temp = temp->next;
	}
	return 0;
}
//遍历打印函数
void print(Node* list) {
	Node* temp = list->next;
	while (temp != list) {
		printf("%d ", temp->data);
		temp = temp->next;
	}
	printf("\n");
}
//测试函数
void test() {
	Node* list = initLoopDoubleLinkList();
	headPush(list, 5);
	headPush(list, 6);
	headPush(list, 7);
	print(list);
	tailPush(list, 2);
	tailPush(list, 3);
	tailPush(list, 4);
	print(list);
	delete(list, 6);
	print(list);
	delete(list, 3);
	print(list);
}
int main() {
	test();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值