实验二 线性表综合实验之《单链表》

来源:互联网 发布:qq空间个性域名注册 编辑:程序博客网 时间:2024/06/05 06:39

实验二 线性表综合实验之《单链表》

一.实验目的

     巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题。

二.实验内容

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

要求如下:

1)用顺序表来实现。

2)用单链表来实现。

3)用双链表实现。

4)用静态链表实现。

5)用间接寻址实现。

三.实验报告

1、操作运算算法图


2、代码

#includeusing namespace std;//单链表的存储templatestruct Node{DataType data;Node*next;};//单链表的实现templateclass LinkList{public:LinkList();LinkList(DataType a[],int n);~LinkList();int Length();DataType Get(int i);int Locate(DataType x);void Insert(int i,DataType x);DataType Delete(int i);void PrintList();private:Node*first;};//遍历操作templatevoid LinkList::PrintList(){Node *p;p=first->next;  //使其指向第一个元素while(p!=NULL){cout<data<<" ";p=p->next;   //指针后移}cout<int LinkList::Length(){Node *p;int count=0;p=first->next;  //使其指向第一个元素while(p!=NULL){p=p->next;   //指针后移count++;}return count;}//按位查找templateDataType LinkList::Get(int i){Node *p;int count=1;p=first->next;while(p!=NULL&&countnext;count++;}if(p==NULL) throw"位置";else return p->data;}//按值查找templateint LinkList::Locate(DataType x){Node *p;int count=1;p=first->next;while(p!=NULL){if(p->data==x) return count;p=p->next;count++;}return 0;}//插入操作templatevoid LinkList::Insert(int i,DataType x){Node *p,*s;int count=0;p=first;  //p指向头节点while(p!=NULL&&countnext;count++;}if(p==NULL) throw"位置";else{s=new Node;s->data=x;s->next=p->next;p->next=s;}}//无参构造函数templateLinkList::LinkList(){first=new Node;  //头结点first->next=NULL;}//有参构造函数templateLinkList::LinkList(DataType a[],int n){Node *s,*r;first=new Node;r=first;for(int i=0;i;s->data=a[i];r->next=s;r=s;}r->next=NULL;}//删除操作templateDataType LinkList::Delete(int i){Node *p,*q;int count=0;p=first;DataType x;while(p!=NULL&&countnext;count++;}if(p==NULL||p->next==NULL)  //结点p不存在或其后继结点不存在throw"位置";else{q=p->next;x=q->data;    //暂时存放被删结点p->next=q->next;delete q;return x;}}//析构函数templateLinkList::~LinkList(){Node *q;while(first!=NULL){ q=first;first=first->next;delete q;}}//主函数int main(){int arr[5]={78,98,88,79,67};int flag=0,loc,x,tab,len;  LinkList List(arr,5);   //install an objectcout<<"\n            单链表"<>tab;  switch(tab)  {  case 1:   {cout<<"1.输出表:";    List.PrintList();cout<>loc;    x=List.Get(loc);cout <<"The number is:"<>x;    loc=List.Locate(x);     cout<<"The number's location is:"<>loc;    cout<<"Please input the insert num:";    cin>>x;    List.Insert(loc,x);cout<>loc;    x=List.Delete(loc-1);cout<

3、调试结果

①、遍历操作及输出总学生人数

②、按位查找操作

③、按值查找操作

④、插入操作

⑤、删除操作


原创粉丝点击