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

C语言实现链表的创建,插入,删除和逆序

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

C语言实现链表的创建,插入,删除和逆序

多的不说直接淦代码

#define _CRT_SECURE_NO_WARNINGS
#include
#include 
#include 
#include 
typedef struct linklist {
	int data;
	struct linklist* next;
}node;
void My_printf1(node* head) {//链表的输出
	node* p;
	p = head;
	while (p->next != NULL) {
		printf("%d ", p->next->data);
		p = p->next;
	}
	printf("n");
	return 0;
}
void My_printf(node* head) {//链表的输出(逆序)
	node* p;
	p = head;
	while (p->next!= NULL) {
		printf("%d ", p->data);
		p = p->next;
	}
	printf("n");
	return 0;
}
node* Insert(node* head,int key) {//插入
	node* t = (node*)malloc(sizeof(node));
	node* p;
	node* q=NULL;
	node* hn = head;
	for (p=hn; p && p->data < key; q = p, p = p->next);
	if (p == head) {
		t->data = key;
		t->next = hn;
		hn = t;
	}
	else {
		t->data = key;
		t->next = q->next;
		q->next = t;
	}
	return hn;
}
node* Delet(node* head, int DeletNum) {//删除
	node* h = head;
	node* p;
	node* q = NULL;
	node* t = (node*)malloc(sizeof(node));
	for (p = h; p && (p->data - DeletNum); q = p, p = p->next);
	if (p == head) {
		h->next = h;
		free(p);
	}
	else  {
		q->next = p->next;
		free(p);
	}
	return h;
}
node* OverTurn(node* head) {//逆序
	node* p;
	node* q;
	p = head;
	p = p->next;
	head->next = NULL;
	while (p!=NULL) {
		q = p;
		p = p->next;
		q->next = head;
		head=q;
		
	}
	
	return head;
}
int main() {
	node* head = (node*)malloc(sizeof(node));
	head->next = NULL;
	node* p;
	p= head;
	int num = 0;
	int InsertNum = 0;
	int DeletNum = 0;
	//输入链表元素
	printf("请输入链表的元素个数:n");
	(void)scanf("%d", &num);
	printf("请输入元素n");
	for (int i = 0; i < num;i++) {
		node* t = (node*)malloc(sizeof(node));
		(void)scanf("%d", &t->data);
		p->next = t;
		t->next = NULL;
		p = t;
	}
	//插入元素
	printf("请输入要插入的数字:n");
	scanf("%d", &InsertNum);
	node* hn = Insert(head, InsertNum);
	My_printf1(hn);
	//删除元素
	printf("请输入要删除的数字:n");
	scanf("%d", &DeletNum);
	node* h = Delet(head, DeletNum);
	My_printf1(h);
	//逆序链表
	printf("逆序链表n");
	My_printf(OverTurn(head));
	return 0;
}

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

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

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