链式存储结构的基本操作
情景
很久没有写过博客了,恰逢数据结构试验课给了一个小题目,借此契机,顺便练练打字。
?实验内容
定义一个包含学生信息(学号,姓名,成绩)的的顺序表和链表,使其具有如下功能:
(1) 根据指定学生个数,逐个输入学生信息;
(2) 逐个显示学生表中所有学生的相关信息;
(3) 根据姓名进行查找,返回此学生的学号和成绩;
(4) 根据指定的位置可返回相应的学生信息(学号,姓名,成绩);
(5) 给定一个学生信息,插入到表中指定的位置;
(6) 删除指定位置的学生记录;
(7) 统计表中学生个数。
? 分析
考察线性表和链表的使用,但是两种实现方法的思路大体相同,本博客主要分析链表的实现。链表是很简单和基础的数据结构,常用操作包括插入,遍历,删除等,这里都要用到。
数据结构理解不难,难在应用,这里就是给出了特定的情景,要求应用特定的数据结构来实现特定的需求。
首先,链的基本单位是节点,而这里每个节点存储的是一个学生的信息。秉着世间万物皆对象的思想,我将学生当做是一个对象,节点看做一个对象,链表又看做一个对象。增删查操作封装在链表类中,插入和删除都对链的长度进行维护。为了使代码清晰,将测试这些函数方法的代码都写成函数,分成不同的模块。
学生类
学生类写成一个单独的结构体,包含了基本的信息,还有一个显示学生信息的方法print()
struct Student{
int sno;
string sname;
double score;
Student(){
this->sno =-1;
this->sname = "";
this->score = 0.0;
}
//display the message of student
void print(){
printf("student | no: %d | name: %s | score: %.1f \n", sno, sname.c_str(), score);
}
//set data of studnet
void SetData(int no, string name, double score){
this->sno = no;
this->sname = name;
this->score = score;
}
};
节点结构
节点包含一个学生结构体,这里我选择不用指针,其实也差不多。
struct Node{
Student data;
Node *next;
Node (int id, string name, double score){
this->data.SetData(id,name,score);
this->next = NULL;
}
};
链表结构
链表结构代码稍长,封装了不少的函数。
getdata()是获取输入,初始化链表。
show()实现逐个显示学生表中所有学生的相关信息;
SearchByName() 和 SearchByIndex() 是更具不同的信息查找节点,思路几乎一致,注意我选择
将查找到的节点返回,在外面对获取的节点作输出操作,这样一定程度上增强了代码的复用性。
Remove()实现删除节点,分三种情况处理,需要小心读取空指针之类的错误。
class StuList{
private:
Node* head = NULL;
int size = 0; //the total studnet number in the list
//insert an node into the list and return the pointer of new node
Node* Insert(Student stu){
Node* temp = new Node(stu.sno, stu.sname, stu.score);
if (size == 0){
//insert to the first node
this->head = temp;
}
else{
Node *nowat = head;
while (nowat->next != NULL) nowat = nowat->next;
nowat->next = temp;
}
size++;
return temp;
}
public:
//get input data and init the list
void getdata(){
Student temp;
int num, sno;
string name;
double score;
cout << "pleace input the students number you want to input : ";
cin >> num;
for (int i = 0; i < num; i++){
cout << "id, name, score : >";
cin >> sno >> name >> score;
temp.SetData(sno, name, score);
Insert(temp);
}
cout << "get data over! \n\n";
}
//dispaly the list
void show(){
printf("=============================================\n");
printf("the total number of student is %d \n", size);
Node *nowat = head;
while (nowat != NULL){
nowat->data.print();
nowat = nowat->next;
}
printf("=============================================\n");
}
// search the student by name and return the pointer to Node
Node* SearchByName(string name){
if (size == 0) return NULL;
Node