[C++] 数据结构——顺序表 →→→→→进入此内容的聊天室

来自 , 2021-03-29, 写在 C++, 查看 175 次.
URL http://www.code666.cn/view/596dedf4
  1. #include <iostream>
  2. #include<stdlib.h>
  3. #include<iomanip>
  4. using namespace std;
  5.  
  6. typedef int ElemType;
  7. class SeqList
  8. {
  9.     private:
  10.     ElemType *list;
  11.     int maxsize;
  12.     int length;
  13.     public:
  14.     SeqList(int max=0);
  15.     ~SeqList(void);
  16.     bool ListEmpty(void);
  17.     int ListLength(void);
  18.     void ListTraverse(void);
  19.     int LocateElem(int i,ElemType e);
  20.     void ListInsert(ElemType &item,int i);
  21.     ElemType ListDelete(int i);
  22.     ElemType GetElem(int i);
  23. };
  24. SeqList::SeqList(int max)
  25. {
  26.     maxsize=max;
  27.     length=0;
  28.     list=new ElemType[maxsize];
  29.  
  30. }
  31. SeqList::~SeqList(void)
  32. {
  33.     delete []list;
  34. }
  35. bool SeqList::ListEmpty(void)
  36. {
  37.     if(length==0)
  38.     return true;
  39.     else
  40.     return false ;
  41. }
  42. int SeqList::ListLength(void)
  43. {
  44.     return length;
  45. }
  46. void SeqList::ListTraverse(void)
  47. {
  48.     if(!ListEmpty())
  49.     for(int i=0;i<length ;i++)
  50.     cout<<setw(4)<<list[i];
  51.     cout<<endl;
  52. }
  53. void SeqList::ListInsert(ElemType &item,int i)
  54. {
  55.     if(length==maxsize)
  56.     {
  57.         cout<<"顺序表已满"<<endl;
  58.         exit(0);
  59.     }
  60.  
  61.     if(i<0||i>length)
  62.     {
  63.         cout<<"参数i出错"<<endl;
  64.         exit(0);
  65.     }
  66.     for(int j=length;j>i;j--)
  67.     list[j]=list[j-1];
  68.     list[i]=item;
  69.     length++;
  70. }
  71. ElemType SeqList::ListDelete(int i)
  72. {
  73.     if(length==0)
  74.     {
  75.         cout<<"顺序表已空"<<endl;
  76.         exit(0);
  77.     }
  78.     if(i<0||i>length-1)
  79.     {
  80.         cout<<"参数i出错"<<endl;
  81.         exit(0);
  82.     }
  83.     ElemType x=list[i];
  84.     for(int j=i;j<length-1;j++)
  85.     list[j]=list[j+1];
  86.     length--;
  87.     return x;
  88. }
  89. ElemType SeqList::GetElem(int i)
  90. {
  91.     if(i<0||i>length-1)
  92.     {
  93.         cout<<"参数i出错"<<endl;
  94.         exit(0);
  95.     }
  96.     return list[i];
  97. }
  98. int main()
  99. {
  100.     SeqList mylist(100);
  101.     int i,a[]={6,8,16,2,34,56,7,10,22,45};
  102.     for(i=0;i<10;i++)
  103.     mylist.ListInsert(a[i],i);
  104.     cout<<"插入后顺序表";
  105.     mylist.ListTraverse();
  106.     mylist.ListDelete(4);
  107.     cout<<"删除后顺序表";
  108.     mylist.ListTraverse();
  109.     return 0;
  110. }

回复 "数据结构——顺序表"

这儿你可以回复上面这条便签

captcha