SQList 实现

sqlist.h
#ifndef SQLIST_H
#define SQLIST_H


typedef int ElemType;


typedef  struct {
    ElemType *elem;
    int length;
    int size;

} SQList;

void InitSqlList(SQList *sqlist);
void  SQListPrint(SQList sqList);
int  InsertSqList(SQList *sqlist,int i,ElemType elem);
int  DeleteSqList(SQList *sqlist,int i);

#endif


sqlist.c
#include 
#include "SQLIST_H"

#define MAXSIZE 200
//1 申请对象指针空间
//2 长度赋初始值
//3 size赋初始值
void InitSqlList(SQList *sqlist){
    sqlist->elem=(ElemType*)malloc(MAXSIZE*sizeof(ElemType));
    if(!sqlist->elem)
    {
        printf("init fail\n");
        exit(0);
    }else{
       printf("init success\n");
    }
    sqlist->length=0;
    sqlist->size=MAXSIZE;

}



void  SQListPrint(SQList sqList){
    printf("SQLElems->length:%d\n",sqList.length);
    printf("[");
    for(int i=0;ilength: %d size:%d\n",sqList.length,sqList.size);

}


//算法步骤
//1.判断i位置是否越界
//2.判断sqlList是否满
//3.判断当前i是否超过集合的元素长度 没有就直接后面加有则第4步
//3. 将第n到第i后移
//4. 在第i个位置插入
//5. 容器长度加1

//算法分析
//算法时间主要耗时在节点的移动上
//如果再尾节点插入就在插入
//如果头节点插入则需要移动全部
//假设在n个节点插入 有

  int  InsertSqList(SQList *sqList,int i,ElemType elem){
    if(i<1 || i>sqList->size){
        return -1;
    }

    if(sqList->length==sqList->size){
        return -1;
    }

    if(sqList->length==0){
      sqList->elem[sqList->length]=elem;
    }else if((sqList->length)elem[sqList->length]=elem;
    }else{
        int len=sqList->length;
        for(;i<=len;len--){
            sqList->elem[len]=sqList->elem[len-1];

        }
        sqList->elem[len]=elem;

    }

    sqList->length=sqList->length+1;
    return 0;

}



//算法步骤
//1.判断位置是否合法
//2.从i位置开始后面的元素覆盖前面的元素
//3.length 长度减1

int  DeleteSqList(SQList *sqlist,int i){

    if(i<1 || i>sqlist->length){
        return -1;
    }
    int len=sqlist->length;
    for(;ielem[i-1]=sqlist->elem[i];
    }
    sqlist->length=sqlist->length-1;
    return 0;

}




main.c
#include 
#include "SQLIST_H"

SQList sqList;

void InitSqlList(SQList *sqlist);
void  SQListPrint(SQList sqList);
int  InsertSqList(SQList *sqlist,int i,ElemType elem);
int  DeleteSqList(SQList *sqlist,int i);
void  main(){

    printf("init sqlList\n");

    InitSqlList(&sqList);
    SQListPrint(sqList);
    InsertSqList(&sqList,1,1);
    SQListPrint(sqList);
    InsertSqList(&sqList,1,2);
    //InsertSqList(&sqList,2,2);
    SQListPrint(sqList);
    InsertSqList(&sqList,3,3);
    SQListPrint(sqList);
    InsertSqList(&sqList,100,100);
    SQListPrint(sqList);
    DeleteSqList(&sqList,1);
    DeleteSqList(&sqList,3);
    SQListPrint(sqList);
}


你可能感兴趣的:(SQList 实现)