.建立一个N个学生成绩的顺序表,对表进行插入、删除、查找等操作。分别输出结果。
要求如下:
1)用顺序表来实现。
2)用单链表来实现
#include<iostream.h>
struct Node
{
int data;
Node *next;
};
class LinkList
{
public:
LinkList();
LinkList(int a[],int n);
~LinkList();
int Locate(int x);
void Insert(int i,int x);
int Delete(int i);
void PrintList();
private:
Node *first;
};
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,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;
}
}
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;
}
void main()
{
int score[5]={98,60,85,77,90};
LinkList L(score,5);
cout<<"执行插入操作前的数据为:"<<endl;
L.PrintList();
L.Insert(1,100);
cout<<"执行插入操作后的数据为:"<<endl;
L.PrintList();
cout<<"值为60的元素的位置为:";
cout<<L.Locate(60)<<endl;
cout<<"执行删除操作前的数据为:"<<endl;
L.PrintList();
L.Delete(6);
cout<<"执行删除操作后的数据为:"<<endl;
L.PrintList();
}