线性表的顺序存储结构的实现及其应用(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 }

运行结果如下:

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

原文链接: https://www.cnblogs.com/ECJTUACM-873284962/p/7722663.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/261835

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 下午2:44
下一篇 2023年2月14日 下午2:45

相关推荐