链表的增减改操作

#include <iostream>
#include <Windows.h>
#include <fstream>
using namespace std;
struct students {
		int id;
		char name[20];
		students * next;
	};
students * head = NULL;  //用来装第一个
int num;
void modiflcation(students *, int);
void menu();
void print();
void del();
void add();
int main()
{
	
	
	cout << "请问有几位同学需要录入成绩?:" << endl;
	cin >> num;
	ofstream file;
	file.open("students.txt");
	file << "学生学号   " << "学生名字" << endl;
	
	students * p = NULL;     //用来分配内存
	students * temp = NULL;  //用来每次更新车厢
	for (int i = 0; i < num; i++)
	{
		p = new(students);
		if (i == 0)
		{
			head = p;
		}
		else
		{
			temp->next = p;
		}
		cout << "请问同学的学号为:";
		cin >> p->id;
		file << p->id;
		file << "\t\t";
		cout << "请输入名字" << endl;
		cin >> p->name;
		file << p->name;
		file << endl;
		temp = p;
	}
	temp->next = NULL;
	system("pause");
	system("cls");
	menu();
	file.close();
}

void modiflcation()  //更改函数
{
	students * num_1 = head;
	int id;
	do {
		cout << "请问你要修改那位同学的信息:";
		cin >> id;
	} while (id > num);
	for (int i = 0; i < num; i++)
	{
		if (num_1->id == id)
		{
			cout << "请输入你要更改的id:";
			cin >> num_1->id;
			cout << "请输入你要更改的名字:";
			cin >> num_1->name;
		}
		num_1 = num_1->next;
	}
	num_1 = NULL;
	delete num_1;
	menu();
}

void menu()  //菜单
{
	cout << "1.修改同学的信息" << endl;
	cout << "2.增加新同学" << endl;
	cout << "3.删除同学" << endl;
	cout << "4.查看同学" << endl;
	int chioce;
	cout << "请输入你的选择:";
	cin >> chioce;
	switch (chioce) {
	case 1:
		modiflcation();
		menu();
		break;
	case 2:
		add();
		menu();
		break;
	case 3:
		del();
		print();
		break;
	case 4:
		print();
		break;
	}
}

void add()  //增加同学
{
	students * temp = head;
	int chioce;
	do {
		cout << "请问你要增加第几个同学";
		cin >> chioce;
	} while (chioce > num + 1);

		for(int i = 1; i < chioce -1;i++)
		{
			temp = temp->next;
		}
		students * tempnum = temp->next;
		students * p = NULL;
		p = new (students);
		cout << "请输入id:";
		cin >> p->id;
		cout << "请输入名字";
		cin >> p->name;
		p->next = tempnum;
		temp->next = p;
		num++;  //增加同学数目
		temp = NULL;
		delete temp;
		menu();
}
void print()  //打印同学信息
{
	students *tempnum = head;
	for (int i = 0; i < num; i++)
	{
		cout << tempnum->id;
		cout << tempnum->name;
		tempnum = tempnum->next;
	}
	tempnum = NULL;
	delete tempnum;
	menu();
}
void del()//删除同学信息
{
	int chioce;
	do {
		cout << "请输入你要删除第几个同学";
		cin >> chioce;
	} while (chioce > num);
	students * tempnum = head;
	for (int i = 0; i < chioce-2; i++)
	{
		tempnum = tempnum->next;
	}
	students *temp = tempnum->next;
	tempnum->next = tempnum->next->next;
	tempnum = NULL;
	delete temp;
	num--;
	menu();
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值