存档---
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
#define MAXSIZE 10
#include "SqList.h" void main()
{
SqList myList;
int i = ,x,sum = ,n;
InitList(myList);
scanf("%d",&x);
while(x!=-)//输入的数据以-1作为结束标志
{
if(ListInsert(myList,i,x)==false)
{
printf("错误!\n");
return;
}
i++;
scanf("%d",&x);
}
n = ListLength(myList);
for(i = ;i<=n;i++)
{
x = GetElem(myList,i);
sum = sum+x;
}
printf("%d\n",sum);
ClearList(myList);
}
typedef struct List{
ElemType *elem;
int length;
}SqList; void InitList(SqList &L)
{ //构造一个空的顺序表
L.elem = new ElemType[MAXSIZE];
L.length = ;
} void ClearList(SqList &L)
{ //清空线性表,不销毁
//delete []L.elem;
//L.elem = NULL;
L.length = ;
} int ListLength(SqList L)
{ //求线性表长度
return L.length;
} bool ListInsert(SqList &L,int i,ElemType e)
{ //在线性表L中第i个数据元素之前插入新数据元素e
if(L.length<MAXSIZE)
{
for(int j = ;j<=L.length-i+;j++)
{
L.elem[L.length-j+] = L.elem[L.length-j];
}
L.elem[i-] = e;
L.length++;
return true;
}
else
{
return false;
}
} ElemType GetElem(SqList L,int i)
{ //在线性表L中求序号为i的元素,该元素作为函数返回值
if (i<||i>L.length)
{
printf("i不在[1..n]范围内");
exit(-);
}
return L.elem[i-];
}
运行结果如下: