数据结构之顺序表

使用C语言编写;

基本功能:顺序表的初始化,插入,删除,查找(按索引查找,按值查找)

代码如下:

  1 /*
  2  *创建保存图书信息的顺序表
  3  *@author cfyangxingguo
  4 */
  5 #include <bits/stdc++.h>
  6 
  7 using namespace std;
  8 #define MAXSIZE 1000
  9 
 10 typedef struct{
 11 char no[3];
 12 char name[2];
 13 int price;
 14 }Book;
 15 
 16 typedef struct{
 17 Book *elem;     //存储空间的基地址
 18 int length;     //图书表中当前图书个数
 19 }Sqlist;
 20 
 21 /*
 22  * 顺序表的初始化
 23  *@return 返回true即为创建成功
 24  */
 25 bool InitList(Sqlist &L){
 26     L.elem=new Book[MAXSIZE];//动态分配空间
 27     if(!L.elem) exit(1);
 28     L.length=0;
 29     return true;
 30 }
 31 
 32 /*
 33  *出入到顺序表中
 34 */
 35 bool ListInsert(Sqlist &L,int i,Book e){
 36     if(i<1||i>L.length+1) return false;
 37     if(L.length==MAXSIZE) return false;
 38     for(int j=L.length-1;j>=i-1;j--)
 39     L.elem[j+1]=L.elem[j];
 40     L.elem[i-1]=e;
 41     L.length++;
 42     return true;
 43 }
 44 
 45 /*
 46  *在顺序表中删除某一元素
 47 */
 48 bool ListDelete(Sqlist &L,int i){
 49 if(i<1||i>L.length) return false;
 50 for(int j=i-1;j<L.length;j++)
 51     L.elem[j]=L.elem[j+1];
 52     --L.length;
 53     return true;
 54 }
 55 
 56 /*
 57  *或取某一元素的值
 58 */
 59 bool GetElem(Sqlist L,int i,Book &e){
 60 if(i<1||i>L.length) return false;
 61     e=L.elem[i-1];
 62 return true;
 63 }
 64 /*
 65  *在顺序表中查找某一元素值,查找成功返回1,否则返回0
 66 */
 67 bool LocateList(Sqlist L,Book e){
 68 for(int i=0;i<L.length;i++){
 69 if(strcmp(L.elem[i].no,e.no)&&L.elem[i].price==e.price&&strcmp(L.elem[i].name,e.name)) return true;
 70 }
 71 return false;
 72 }
 73 int main()
 74 {
 75    Sqlist L;
 76    InitList(L);
 77    Book e[5]={{"01","A",10},{"02","B",10},{"03","C",10},{"04","D",10},{"05","E",10}};
 78    for(int i=0;i<=3;i++)
 79     ListInsert(L,i+1,e[i]);
 80     Book e1;
 81     GetElem(L,1,e1);
 82     printf("%s,%s,%d\n",e1.no,e1.name,e1.price);
 83 
 84     for(int i=0;i<L.length;i++)
 85     {
 86     printf("%s,%s,%d\n",L.elem[i].no,L.elem[i].name,L.elem[i].price);
 87     }
 88 
 89     if(LocateList(L,e[0])){
 90     printf("顺序表中有这儿值\n");
 91     }
 92 
 93     if(!LocateList(L,e[4])){
 94     printf("顺序表中没有这儿值\n");
 95     }
 96     e.no
 97     if(ListDelete(L,3))
 98     printf("删除成功\n");
 99     return 0;
100 }

 

posted @ 2019-10-20 20:00  大壞狐狸  阅读(214)  评论(0)    收藏  举报