实验二——单链表

来源:互联网 发布:淘宝原单包店铺推荐 编辑:程序博客网 时间:2024/06/05 16:54
一、实验目的 
巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题。


二、 实验内容 

建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。 

(用单链表实现)


三、源代码

ScoreList.h

#ifndef ScoreList_H //避免重复包含ScoreList.h头文件 #define ScoreList_Hstruct Node{int data;Node *next;};class ScoreList{public:ScoreList();ScoreList(int a[],int n);~ScoreList();void Insert(int i,int x);int Delete(int i); int Locate(int x);int Get(int i);void PrintList();//遍历private:Node *first;};#endif

ScoreList.cpp

#include <iostream>using namespace std;#include"ScoreList.h" ScoreList::ScoreList(){first=new Node;first->next=NULL; }/*ScoreList::ScoreList(int a[],int n)//头插法 {Node *s;first=new Node;first->next=NULL;for(int i=0;i<n;i++){s=new Node;s->data=a[i];s->next=first->next;first->next=s;}}*/ScoreList::ScoreList(int a[],int n)//尾插法{ Node *r,*s;first=new Node;r=first;for(int i=0;i<n;i++){s=new Node;s->data=a[i];r->next=s;r=s;}r->next=NULL;}ScoreList::~ScoreList(){while(first!=NULL){Node *q=first;first=first->next;delete q;}}void ScoreList::PrintList(){Node *p;p=first->next;while(p!=NULL){cout<<p->data<< " ";p=p->next;}cout<<endl; }void ScoreList::Insert(int i,int x){Node *p =first;for (int j=0;j<i-1;j++) p=p->next;    if(p==NULL) throw"位置";    else{Node *t ;t=new Node;    t->data=x;    t->next=p->next;    p->next=t;}}int ScoreList::Delete(int i){    Node *p;p = first;    for(int j=0; j<i-1;j++)    p=p->next;    if(p==NULL||p->next==NULL) throw"位置";    else{Node *q;q=p->next;    int x=q->data;    p->next=q->next;    delete q;    return x;}}int ScoreList::Get(int i) {Node *p;p=first->next;for(int count=0;count<i-1;count++)p=p->next;if(p==NULL) throw"位置";else return p->data;}int ScoreList::Locate(int x) {Node *p;p=first->next;int count=1;while(p!=NULL){if(p->data==x) return count;p=p->next;count++;}return 0;}


ScoreList_main.cpp

#include <iostream>using namespace std;#include"ScoreList.h" int main() {int a[]={99,63,56,77,84,90,50};ScoreList L(a,10);cout<<"所有成绩:";L.PrintList();cout<<"第6个学生成绩:"<<L.Get(6)<<endl;cout<<"成绩为84的学生位置:"<<L.Locate(84)<<endl;cout<<"在第四个位置插入学生成绩100:  ";L.Insert(4,100);L.PrintList();cout<<"删除第三个学生成绩:  ";L.Delete(3);L.PrintList();}

结果



四、总结

尝试用单链表来实现对学生成绩的插入、删除、查找等操作。在完成代码的过程中出现了不少错误,都经过查阅书本和网上搜索解决了问题,进一步了解了单链表的使用。通过这个实验感觉到自己对C++的知识掌握不牢固,熟练度不够高,需要更多的练习。