双链表--学生成绩表

来源:互联网 发布:6city类似软件 编辑:程序博客网 时间:2024/05/22 03:17
#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;  }  
原创粉丝点击