線性表的順序存儲結構的實現及其應用(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("%d\n",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 }

運行結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM