线性表的初始化,增删查操作等
#include<stdio.h>
#define LISTSIZE 100
typedef int DataType;
typedef struct{
DataType items[LISTSIZE];
int length;
}SqList;
// 2-1 init list
int InitList(SqList *L){
L->length = 0;
return 1;
}
// 2-2 length
int ListLength(SqList L){
return L.length;
}
// 2-3 empty
int ListEmpty(SqList L){
if(L.length <= 0) return 1;
else return 0;
}
// 2-4 insert
int ListInsert(SqList *L,int pos,DataType item){
int i;
if(L->length >= LISTSIZE){
printf("it had full,you can insert it\n");
return 0;
}
if(pos<=0 || pos>L->length+1){
printf("you choose position is nosuitbale,please choose the [1,length+1]\n");
return 0;
}
for(i = L->length -1;i>=pos-1;i--){
L->items[i+1] = L->items[i];
}
L->items[pos-1] = item;
L->length++;
return 1;
}
// 2-5 delete
int ListDelete(SqList *L,int pos,DataType *item){
int i;
if(ListEmpty(*L)){
printf("this is a empty List\n");
return 0;
}
if(pos<1||pos>L->length){
printf("delete the position is nosuitbale,the range is [1,length]\n");
return 0;
}
*item = L->items[pos-1];
for (int i = 0; i < L->length; ++i)
{
L->items[i-1] = L->items[i];
/* code */
}
L->length --;
return 1;
}
// 2-6 find
int Find(SqList L,DataType item){
int pos =0;
if(ListEmpty(L)){
printf("this is a empty List\n");
return 0;
}
while(pos<L.length && L.items[pos]!=item){
pos++;
}
if(pos<L.length) return pos+1;
else return 0;
}
// 2-7 get element
int GetElem(SqList L,int pos,DataType *item){
if(ListEmpty(L)) return 0;
if(pos<0 || pos>L.length){
printf("please input again!\n");
return 0;
}
*item = L.items[pos-1];
return 1;
}
// 2-8 TraverseList
int TraverseList(SqList L){
int i;
for(i = 0 ; i <L.length;i++){
printf("%d\t",L.items[i] );
}
printf("\n");
return 0;
}
int main(){
int i;
int data[7] = {0,1,1,2,3,5,8};
DataType item;
SqList fibo;
printf("init list\n");
InitList(&fibo);
for(i = 0; i < 7;i++){
if(!ListInsert(&fibo,i+1,data[i])){
printf("run wrong\n");
return 0;
}
}
printf("\nbefore delete \n");
TraverseList(fibo);
if(!ListDelete(&fibo,7,&item)){
printf("run wrong\n");
return 0;
}
printf("\nafter delete \n");
TraverseList(fibo);
return 1;
}