链表的基本操作(用switch实现命令操作)

自学的C语言可能算法比较垃圾,希望能够指出更好的算法,
以下是C语言链表的一些基本操作,把它弄成链表功能的集合:

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
typedef struct student
{
	int num;
	struct student *next;
}st;
st *creat(int n);//创立节点
void print(st *head);//打印节点
void add(st *head1, int n);//添加节点
void detele(st *head, int n);//删除节点
void creect(st *head, int n);//修改节点
void search(st * head, int temp);//查找节点
int main()
{
	int n,m,o,temp,b,lo;
	st *head;
	cout << "输入创建节点的个数:\n";
	cin >> n;
	head = creat(n);
	cout << "1.添加节点\n";
	cout << "2.打印节点\n";
	cout << "3.删除节点\n";
	cout << "4.修改节点\n";
	cout << "5.查找节点\n";
	cout << "0.退出系统\n";
	cout << "\n请输入指令:  (  0  到   9  ) \n";
	while (1)
	{
		cin >> m;
		if (m == 0) { cout << "成功退出!!\n"; break; }
		switch (m)
		{
		case 1: { cout << "输入添加节点的位置:\n"; cin >> o; add(head,o); break; }
		case 2: {cout << "打印节点数据如下  :\n";              print(head); break; }
		case 3: { cout << "输入删除节点的位置:   \n"; cin >> b; detele(head, b); break; }
		case 4: {cout << "输入修改节点的位置:\n"; cin >> lo; creect(head, lo); break; }
		case 5: {cout << "输入查找的值:\n"; cin >> temp; search(head, temp); break; }
		default: {cout << "没有这个选项,请重新输入:\n"; break; }
		}

	}
	return 0;
}
st *creat(int n)
{
	st *head, *end, *node;
	head = (st*)malloc(sizeof(st));
	end = head;
	printf("请输入节点数据:");
	for (int i = 0; i < n; i++)
	{
		node = (st*)malloc(sizeof(st));
		cin >> node->num;
		end->next = node;
		end = node;
	}
	end->next = NULL;
	return head;
}
void print(st *head)
{
	st *p = head->next;
	while (p)
	{
		printf("%d  ", p->num);
		p = p->next;
	}
}
void add(st *head1, int n)
{
	st *t = head1;
	int i = 1;
	while (i < n&&t != NULL)
	{
		t = t->next;
		i++;
	}
	if (t != NULL)
	{
		st *node = (st*)malloc(sizeof(st));
		cout << "\n请输入节点数据: \n";
		cin >> node->num;
		node->next = t->next;
		t->next = node;
	}
	else
	{
		cout << "该节点不存在!!!!!";
	}
}
void detele(st *head, int n)
{
	st *t;
	int i = 0;
	t = head;
	while (i < n&&t != NULL)
	{
		head = t;
		t = t->next;
		i++;
	}
	if (t != NULL)
	{
		head-> next = t ->next;
		free(t);
	}
	else
	{
		cout << "该节点不存在!!!!!";
	}
}
void creect(st *head, int n)
{
	st *t = head;
	int i = 0;
	while (i < n&&t != NULL)
	{
		t = t->next;
		i++;
	}
	if (t != NULL)
	{
		cout << "\n输入新建节点的数据:\n";
		cin >> t->num;
	}
	else
	{
		cout << "该节点不存在!!!!!";
	}
}
void search(st * head, int temp)
{
	st *t = head;
	int i = 0;
	while (t->num != temp && t != NULL)
	{
		t = t->next;
		i++;
	}
	if (t != NULL)
	{
		cout << "\n该节点的位置为\n:  "<<i;
	}
	else
	{
		cout << "该节点不存在!!!!";
	}
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值