《数据结构》实验二:
线性表综合实验
一.实验目的
巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题
二.实验内容
1.建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。
要求如下:
1)用顺序表来实现。
2)用单链表来实现。
3)用双链表实现。
4)用静态链表实现。
5)用间接寻址实现。
双链表的实现
#include
using namespace std;
const int M=100;
//双链表的存储
struct DulNode
{
int data;
DulNode *prior,*next;
};
class LinkList{
public:
LinkList();
LinkList(int a[],int n);
~LinkList();
int Length();
int Get(int i);
int Locate(int x);
void Insert(int i,int x);
int Delete(int i);
void PrintList();
private:
DulNode *first;
};
//遍历操作
void LinkList::PrintList()
{
DulNode *p;
p=first->next; //使其指向第一个元素
while(p!=NULL)
{
cout<data<<" ";
p=p->next; //指针后移
}
cout<next; //使其指向第一个元素
while(p!=NULL)
{
p=p->next; //指针后移
count++;
}
return count;
}
//按位查找
int LinkList::Get(int i)
{
DulNode *p;
int count=1;
p=first->next;
while(p!=NULL&&countnext;
count++;
}
if(p==NULL) throw"位置";
else return p->data;
}
//按值查找
int LinkList::Locate(int x)
{
DulNode *p;
int count=1;
p=first->next;
while(p!=NULL)
{
if(p->data==x) return count;
p=p->next;
count++;
}
return 0;
}
//插入操作
void LinkList::Insert(int i,int x)
{
DulNode *p,*s;
int count=0;
p=first; //p指向头节点
while(p!=NULL&&countnext;
count++;
}
if(p==NULL) throw"位置";
else
{ s=new DulNode;s->data=x;
s->prior=p;
s->next=p->next;
p->next->prior=s;
p->next=s;
}
}
//无参构造函数
LinkList::LinkList()
{
first=new DulNode; //头结点
first->next=NULL;
}
//有参构造函数
LinkList::LinkList(int a[],int n)
{
DulNode *s,*r;
first=new DulNode;r=first;
for(int i=0;idata=a[i];
s->prior=r;
r->next=s;
r=s;
}
r->next=NULL;
}
//删除操作
int LinkList::Delete(int i)
{
DulNode *p;
int count=0;
p=first;int x;
while(p!=NULL&&countnext;
count++;
}
if(p==NULL) //结点p不存在或其后继结点不存在
throw"位置";
else{
x=p->data;
(p->prior)->next=p->next;
if(p->next!=NULL) (p->next)->prior=p->prior;
delete p;
return x;
}
}
//析构函数
LinkList::~LinkList()
{
DulNode *q;
while(first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}
int main()
{
int x,n,loc,len,tab;
cout<<"\t\t\t\t\t录入学生成绩信息"<>n;
for(j=0;j>d[j];
}
LinkList List(d,n);
while (1)
{
cout<<"\t\t\t\t\t********** 双链表的实现 **********"<>tab;
switch(tab)
{
case 1:
{
cout<<"\t\t\t\t\t1.输出学生成绩 :";
List.PrintList();
cout<>loc;
x=List.Get(loc);
cout <<"\t\t\t\t\t要查找的成绩是:"<>x;
loc=List.Locate(x);
cout<<"\t\t\t\t\t输入要查找成绩的位置是:"<>loc;
cout<<"\t\t\t\t\t输入要插入的成绩:";
cin>>x;
List.Insert(loc,x);
cout<>loc;
x=List.Delete(loc);
cout<
执行结果截图:
1)录入并输出学生成绩
2)输出表长
3)按位查找
4)按值查找
5)插入操作
6)插入成功后输出成绩
7)
删除操作
8)插入成功后输出成绩