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

老规矩直接淦代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
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("%d\n", 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;
}

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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值