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

vs 2019实现单链表的创建、插入、删除、查找、输入

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

vs 2019实现单链表的创建、插入、删除、查找、输入

#include
#include

struct List {
	int date;
	struct List* next;
};

void creatList(List** obj) {
	int a, h[20] = { 0 };

	List* head = *obj;
	printf("请选择输入元素个数和元素值:");
	scanf_s("%d", &a);
	for (int i = 0; i < a; i++) {
		scanf_s("%d", &h[i]);
		List* node = (List*)malloc(sizeof(List));
		node->next = NULL;
		head->next = node;
		node->date = h[i];
		head = head->next;
	}
}

void insertListIndex(List** obj) {
	int m, n;
	printf("请输入要插入的元素和插入位置:");
	scanf_s("%d %d", &m, &n);
	List* head = *obj;
	List* node = (List*)malloc(sizeof(List));
	if (node == NULL) {
		printf("内存分配不成功!n");
	}
	else {
		for (int i = 1; i < n; i++) {
			head = head->next;
		}
		node->next = head->next;
		head->next = node;
	}
}

void deleteListIndex(List** obj) {
	int m;
	List* head = *obj, * q;
	printf("请输入要删除的元素的位置:");
	scanf_s("%d", &m);
	for (int i = 1; i < m; i++) {
		head = head->next;
	}
	q = head->next;
	head->next = head->next->next;
	free(q);
}

void findListInext(List* obj) {
	int m;
	List* head = obj;
	printf("请输入要查找的元素的位置:");
	scanf_s("%d", &m);
	for (int i = 0; i < m; i++) {
		head = head->next;
	}
	printf("元素是:%dn", head->date);
}

void printList(List* obj) {
	List* head = obj;
	while (head->next != NULL) {
		head = head->next;
		printf("%d ", head->date);
	}
	printf("n");
}

void destroyList(List** obj) {  //销毁链表
	List* node = (*obj);
	while (node != NULL) {
		node = node->next;  //p指向下一个待销毁的结点
		free(*obj);  //销毁当前结点
		(*obj) = node;   //
	}
	//(*h)=NULL; 此句可省
}

int main() {
	int a;
	List* head = (List*)malloc(sizeof(List)); 
	head->next = NULL;
	printf("1:创建链表 2:插入 3:删除 4:查找 5:输出 0:退出n");
	while (1) {
		printf("请选择操作:");
		scanf_s("%d", &a);
		if (a == 1) creatList(&head);
		else if (a == 2) insertListIndex(&head);
		else if (a == 3) deleteListIndex(&head);
		else if (a == 4) findListInext(head);
		else if (a == 5) printList(head);
		else if (a == 0) break;
		else printf("输入错误!");
		printf("n");
	}
	destroyList(&head);
	return 0;

 

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

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

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