实验二 线性表综合实验——单链表

来源:互联网 发布:java 打印内存地址 编辑:程序博客网 时间:2024/05/19 16:20

一、实验目的

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

二、.实验内容

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

三、程序代码

#include<iostream>using namespace std;struct Node{int data;Node *next;};class LinkList{private:Node *first;public:LinkList();LinkList(int a[],int n);~LinkList();int Locate(int x);void Insert(int i,int x);int Delete(int i);void PrintList();};LinkList::LinkList(){first=new Node;first->next=NULL;}LinkList::LinkList(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;}LinkList::~LinkList(){Node *q=NULL;while(first!=NULL){q=first;first=first->next;delete q;}}void LinkList::Insert(int i,int x){Node *p=first,*s=NULL;int count=0;while(p!=NULL&&count<i-1){p=p->next;count++;}if(p==NULL)throw"位置";else{s=new Node;s->data=x;s->next=p->next;p->next=s;}}int LinkList::Delete(int i){Node *p=first,*q=NULL;int x;int count=0;while(p!=NULL&&count<i-1){p=p->next;count++;}if(p==NULL||p->next==NULL)throw"位置";else{q=p->next;x=q->data;p->next=q->next;delete q;return x;}return 0;}int LinkList::Locate(int x){Node *p=first->next;int count=1;while(p!=NULL){if(p->data==x)return count;p=p->next;count++;}return 0;}void LinkList::PrintList(){Node *p=first->next;while(p!=NULL){cout<<p->data<<" ";p=p->next;}cout<<endl;}int main(){int r[5]={91,92,94,95,96};LinkList L(r,5);cout<<"执行插入操作前数据为:"<<endl;L.PrintList();cout<<"在第三个位置插入成绩93"<<endl;try{L.Insert(3,93);}catch(char *s){cout<<s<<endl;}cout<<"执行插入操作后数据为:"<<endl;L.PrintList();cout<<"成绩为93的学生位置为:";cout<<L.Locate(93)<<endl;cout<<"执行删除操作前数据为:"<<endl;L.PrintList();cout<<"删除第一个成绩"<<endl;try{L.Delete(1);}catch(char *s){cout<<s<<endl;}cout<<"执行删除操作后数据为:"<<endl;L.PrintList();return 0;}


原创粉丝点击