C++ //习题 7.8 写一个函数del,用来删除动态链表中一个指定的结点(由实参指定某一学号,表示要删除该学生结点)。

2023-12-19 06:47:35

C++程序设计 (第三版) 谭浩强 习题7.8

习题 7.8 写一个函数del,用来删除动态链表中一个指定的结点(由实参指定某一学号,表示要删除该学生结点)。

IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。

?

代码块
方法:使用指针,结构体,自定义类型,函数的模块化设计,分配内存
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

const int N = 3;

//自定义学生类型
typedef struct Student{
	int num;
	string name;
	double score;
	Student *next;
}Student;

//初始化学生并生成头结点,头结点num存储总共学生人数
void initialStu(Student **stu, int n){
	*stu = new Student;
	Student *head = *stu;
	head->num = n;
	head->next = NULL;
}

//链表输入学生信息
void create(Student *stu, int n){
	Student *p = stu->next;
	Student *q = stu;
	cout<<"Enter "<<n<<" Student Info:"<<endl;
	for(int i = 0; i < n; i++){
		p = new Student;
		cout<<"Enter No."<<i + 1<<" Student Number(100 ~ 999): ";
		cin>>p->num;
		while(p->num < 100 || p->num > 999){
			cout<<"Number Error! Retry!\nEnter No."<<i + 1<<" Student Number(100 ~ 999): ";
			cin>>p->num;
		}

		fflush(stdin);
		cout<<"Enter No."<<i + 1<<" Student Name: ";
		getline(cin, p->name);

		cout<<"Enter No."<<i + 1<<" Student Score(0 ~ 100): ";
		cin>>p->score;
		while(p->score < 0 || p->score > 100){
			cout<<"Score Error! Retry!\nEnter No."<<i + 1<<" Student Score(0 ~ 100): ";
			cin>>p->score;
		}

		p->next = NULL;
		q->next = p;
		p = p->next;
		q = q->next;
		cout<<endl;
	}
	cout<<endl;
}

//打印链表学生信息
void print(Student *stu, int n){
	cout<<"Student Info: "<<endl;
	for(Student *p = stu->next; p != NULL; p = p->next){
		cout<<setiosflags(ios::right);
		cout<<"Number: "<<setw(3)<<p->num<<" Name: "<<setw(10)<<p->name<<" Score: ";
		cout<<setiosflags(ios::fixed)<<setprecision(2);
		cout<<setw(5)<<p->score<<endl;
	}
	cout<<endl<<endl;
}

//删除输入的学号对应的学生信息
void del(Student *stu, int *num){
	cout<<"Enter the student number you want to delete: ";
	cin>>*num;

	Student *p = stu->next;
	Student *q = stu;
	for(; p != NULL; p = p->next, q = q->next){
		if(p->num == *num){
			q->next = p->next;
			break;
		}
	}
}

int main(){
	Student *stu = NULL;
	int *num = new int;

	initialStu(&stu, N);
	create(stu, N);
	print(stu, N);
	del(stu, num);
	print(stu, N);

	delete stu;
	delete num;
	
	system("pause");
    return 0;
}

文章来源:https://blog.csdn.net/navicheung/article/details/135074052
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。