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

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

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

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

 

代码块
方法:使用指针,结构体,自定义类型,函数的模块化设计,分配内存
#include 
#include 
#include 
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;
}

你可能感兴趣的:(#,C++程序设计,(第三版),谭浩强,课后习题,C/C++,c++,链表,算法)