栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言实现双向链表的创建,删除以及头插元素

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言实现双向链表的创建,删除以及头插元素

老规矩直接淦代码:

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
typedef struct dolinklist {
	int data;
	struct dolinklist* prior;
	struct dolinklist* next;
}node;
node* Creatlist() {//头节点创建
	node* head = (node*)malloc(sizeof(node));
	assert(head);
	head->next = head->prior = NULL;
	return head;
}
void  Initlist(node* head,int num) {
	if (head->next != NULL) {
		node* tmp = head;
		while (tmp->next) {
			tmp = tmp->next;
		}
		node* p = (node*)malloc(sizeof(node));
		p->data = num;
		p->next = NULL;
		p->prior = tmp;
		tmp->next = p;
	}
	else {
		node* p = (node*)malloc(sizeof(node));
		p->data = num;
		p->next = NULL;
		p->prior = head;
		head->next = p;
	}

}
void display(node* head) {//双向链表的打印
	if (head->next != NULL) {
		node* tmp = head;
		while (tmp->next) {
			tmp = tmp->next;
			printf("%d ", tmp->data);
		}
		printf("n");
	}
	else {
		printf("no num");
	}
}
node* Delet(node* head, int num) {
	node* p;
	p = head;
	if (p->next == NULL) {
		printf("无元素删除n");
	}
	else {
		p = p->next;
		//printf("%dn", p->data);
		for (p; p && (p->data - num); p = p->next);
		if (p->next == NULL) {
			p->prior->next = NULL;
			free(p);
		}
		else {
			p->prior->next = p->next;
			p->next->prior = p->prior;
			free(p);
		}
	}
	return head;
}
node* Insert(node* head, int num) {//头插一个节点
	node* p = head;
	node* t = (node*)malloc(sizeof(node));
	p = p->next;
	t->data = num;
	t->next = p;
	t->prior = p->prior;
	p->prior->next = t;
	p->prior = t;
	return head;
}

int main() {
	node* head = Creatlist();
	node* p;
	int n = 0;
	int arr[1024] = { 0 };
	int deletnum = 0;
	int Insertnum = 0;
	//输入链表元素
	printf("请输入要插入的元素个数:n");
	scanf("%d", &n);
	printf("请输入元素:n");
	for (int i = 0; i < n; i++) {
		(void)scanf("%d", &arr[i]);
		Initlist(head, arr[i]);
	}
	//打印;链表元素
	display(head);
	//删除链表元素
	printf("请输入要删除的元素:n");
	scanf("%d", &deletnum);
	node* hn=Delet(head,deletnum);
	display(hn);
	//增添链表元素(头插)
	printf("请输入要增加的数字:n");
	scanf("%d", &Insertnum);
	node* hn1=Insert(hn, Insertnum);
	display(hn);
	return 0;
}

其他插还没学会.......

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/510153.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号