线性表的顺序存储结构的实现及其应用(C/C++实现)

时间:2022-05-07
本文章向大家介绍线性表的顺序存储结构的实现及其应用(C/C++实现),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

存档---

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 typedef int ElemType;
 4 #define MAXSIZE 10
 5 #include "SqList.h"
 6 
 7 void main()
 8 {
 9     SqList myList;
10     int i = 1,x,sum = 0,n;
11     InitList(myList);
12     scanf("%d",&x);
13     while(x!=-1)//输入的数据以-1作为结束标志 
14     {
15         if(ListInsert(myList,i,x)==false)
16         {
17             printf("错误!n");
18             return;
19         }
20         i++;
21         scanf("%d",&x);
22     }
23     n = ListLength(myList);
24     for(i = 1;i<=n;i++)
25     {
26         x = GetElem(myList,i);
27         sum = sum+x;
28     }
29     printf("%dn",sum);
30     ClearList(myList);
31 }
 1 typedef struct List{
 2     ElemType *elem;
 3     int length;
 4 }SqList;
 5 
 6 void InitList(SqList &L)
 7 {    //构造一个空的顺序表 
 8     L.elem = new ElemType[MAXSIZE];
 9     L.length = 0;
10 }
11 
12 void ClearList(SqList &L)
13 {    //清空线性表,不销毁 
14     //delete []L.elem;
15     //L.elem = NULL;
16     L.length = 0;
17 }
18 
19 int ListLength(SqList L)
20 {    //求线性表长度 
21     return L.length;
22 }
23 
24 bool ListInsert(SqList &L,int i,ElemType e)
25 {    //在线性表L中第i个数据元素之前插入新数据元素e 
26     if(L.length<MAXSIZE)
27     {
28         for(int j = 1;j<=L.length-i+1;j++)
29         {
30             L.elem[L.length-j+1] = L.elem[L.length-j];
31         }
32         L.elem[i-1] = e;
33         L.length++;
34         return true;
35     }
36     else
37     {
38         return false;
39     }
40 }
41 
42 ElemType GetElem(SqList L,int i)
43 {    //在线性表L中求序号为i的元素,该元素作为函数返回值 
44     if (i<1||i>L.length)
45     {
46         printf("i不在[1..n]范围内");
47         exit(-2);
48     }
49     return L.elem[i-1];
50 }

运行结果如下: