#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef double ElementType;
typedef struct sqlist
{
ElementType data[MAXSIZE];
int length;
}Sqlist;
void CreatList(Sqlist* L)
{
int i;
double data[5] = { 1,2,3,4,5 };
/*这一步不用,这申请空间的是链表才用,顺序表在定义的时候就分配好了一段空间*/
/* L = (Sqlist*)malloc(sizeof(Sqlist));*/
L->length = 0;
for (i = 0; i < 5; i++)
{
L->data[i] = data[i];
L->length++;//可直接++
}
}
ElementType GetElement(Sqlist* L, int i)
{
return L->data[i];
}
void TraverseList(Sqlist* L)
{
int j;
for (j = 0; j < L->length; j++) {
printf("%.1lf ", L->data[j]);//这样更清晰一些
}
printf("\n");
}
void SearchList(Sqlist* L, ElementType x)
{
int i = 0;
for (i = 0; i < L->length; i++)
if (L->data[i] == x)
{
printf("the position is %d\n", i);
break;
}
if (i<0||i == L->length)//i小于0也应该报错
printf("not be founded\n");
}
int InsertList(Sqlist* L, int i, ElementType x)
{
int k;
if (L->length == MAXSIZE)//表满
return 0;
if (i<1 || i>L->length - 1)
return 0;
if (i <= L->length - 1) {
for (k = --L->length; k >=i; k--)/*k应该赋值为length-1,应该把i下标的位置的元素也往后移*/
L->data[k] = L->data[k - 1];
}
L->data[i-1] = x; //应该在下标为i-1的地方插入x
L->length++;
return 1;
}
int DeleteList(Sqlist* L, int i)
{
int k ;
if (L->length == 0)
return 0;
if (i<0 || i>L->length - 1)
return 0;
if (i < L->length) {
for (k = i-1; k < L->length; k++)//i-1下标的元素应该被覆盖
L->data[k] = L->data[k + 1];
}
L->length--;
return 1;
}
int main() {
Sqlist L;
CreatList(&L);
TraverseList(&L);
if(!GetElement(&L, 1))
printf("return error!\n");
SearchList(&L, 3);
InsertList(&L, 2, 10);
TraverseList(&L);
DeleteList(&L, 4);
TraverseList(&L);
return 0;
}
|