课堂小随笔-顺序表的插删查
1 //lqs原创,已上传blog,侵权必究 2 #pragma GCC optimize(2)//O2 3 #include4 using namespace std; 5 const int M=10000;//最大多少个数组 6 typedef struct node 7 { 8 int a[M];//数据域 9 int Last;//末下标 10 }*List; 11 int n; 12 List MakeEmpty(List L)//建立空表 13 { 14 L=(List)malloc(sizeof(struct node)); 15 L->Last=-1; 16 return L; 17 } 18 int Find(List L,int x)//查找函数 19 { 20 int i=0; 21 while(i<=L->Last&&L->a[i]!=x) 22 i++; 23 if(i>L->Last) 24 return -1; 25 else 26 return i; 27 } 28 bool Insert(List L,int p,int i)//插入函数 29 { 30 int j; 31 if(L->Last==M-1) 32 { 33 cout<<"表已经满了"<<endl; 34 return false; 35 } 36 if(i<1||i>L->Last+2) 37 { 38 cout<<"位置不合法"<<endl; 39 return false; 40 } 41 for(j=L->Last;j>=i-1;j--) 42 { 43 L->a[j+1]=L->a[j]; 44 } 45 L->a[i-1]=p; 46 L->Last++; 47 return true; 48 49 } 50 bool Delete(List L,int r)//删除函数 51 { 52 int j; 53 if(r<1||r>L->Last+1) 54 { 55 cout<<"要删除的元素不存在"<<endl; 56 return false; 57 } 58 for(j=r;j<=L->Last;j++) 59 { 60 L->a[j-1]=L->a[j]; 61 } 62 L->Last--; 63 return true; 64 } 65 int main() 66 { 67 ios::sync_with_stdio(false);//快输,不懂的去我博客 68 List L=MakeEmpty(L);//建表 69 cin>>n; 70 for(register int i=0;i ) 71 { 72 cin>>L->a[i]; 73 } 74 L->Last=n-1;//把末下标确定下来 75 int x; 76 cin>>x; 77 if(Find(L,x)==-1)//判断条件,分找到和没找到 78 cout<<"没有找到您所要找的元素"<<endl; 79 else 80 { 81 cout< //如果查找到了就输出那个下表就可以了 82 } 83 int i; 84 int p; 85 cin>>p>>i; 86 Insert(L,p,i);//开始插入 87 cout<<"插入之后的元素是:"<<' '; 88 for(register int j=0;j<=L->Last;j++)//输出插入之后的元素都有那些 89 cout< a[j]<<' '; 90 cout<<endl; 91 int r; 92 cin>>r; 93 Delete(L,r);//开始删除 94 cout<<"删除之后的元素是:"<<' '; 95 for(register int j=0;j<=L->Last;j++)//输出删除之后的元素都有那些 96 { 97 cout< a[j]<<' '; 98 } 99 cout< //换行好看显美观 100 return 0; 101 }
课上写的顺序表,内容比较简单,看注释就好了