双链表(纯C语言实现)

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值