您的位置:首页 > 其它

双链表--学生成绩表

2017-10-11 21:39 148 查看
#include<iostream>
using namespace std;
struct Node
{
int data;

Node *prior;
Node *next;
};
class DoubleList
{
private:
Node *first;
public:
DoubleList();
DoubleList(int a[],int n);
~DoubleList();
void Insert(int i,int x);
int Delete(int i);

void PrintList();
};
DoubleList::DoubleList()
{
first=new Node;
first->next=NULL;
}
DoubleList::DoubleList(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];
s->next=NULL;
r->next=s;
s->prior=r;
r=s;
}

r->next=NULL;
}
DoubleList::~DoubleList()
{
Node *q=NULL;

while(first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}
void DoubleList::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->prior=p;
s->next=p->next;
p->next->prior=s;
p->next=s;
}
}
int DoubleList::Delete(int i)
{
Node *p=first;
int count=0;
while(p!=NULL&&count<i)
{
p=p->next;
count++;
}
if(p==NULL)
throw"位置";
else{
(p->prior)->next=p->next;

(p->next)->prior=p->prior;
free(p);
}
return 0;
}

void DoubleList::PrintList()
{
Node *p=first->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
int stu_score[5]={88,92,52,68,78};
DoubleList L(stu_score,5);
cout<<"成绩表数据为:"<<endl;
L.PrintList();
cout<<"在第三个位置插入成绩"<<endl;
try
{
L.Insert(3,78);
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<"插入后数成绩表为:"<<endl;
L.PrintList();
cout<<"删除前成绩表为:"<<endl;
L.PrintList();
cout<<"删除第一个成绩"<<endl;
try
{
L.Delete(1);
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<"删除后成绩表为:"<<endl;
L.PrintList();

return 0;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: