線性表的基本操作

線性表的動態分配順序存取結構
LIST_INT_SIZE 100 線性表存儲空間初始分配量
LISTINCREMENT 10 線性表存儲空間的分配增量

typedef struct
{
    ElemType *elem;
    int length;
    int listsize;
}sqlist;

構造一個空的線性表

status initlist(sqlist&l)//&爲C++的引用C可用sqlist*l來替換
{
     l.elem=(ElemType*)malloc(LIST_INT_SIZE*sizeof(int));
     //l.elem=new int[LIST__INT_SIZE] new爲c++中函數
     if(!l.elem)
        exit(0);
     l.length=0;
     l.listsize=LIST_INT_SIZE;
     return 1}

清空線性表

status clearlist(sqlist&l)
{
     l.length=0;
     return 1;
}

銷燬線性表

status destroy(sqlist&l)
{
    fread(l.elem);//free函數屬於頭文件stdlib.h,釋放存儲空間,將線性表的存儲空間釋放掉,也就是銷燬。
    l.elem=NULL;//將指針變量賦值NULL的意思就是此指針變量不指向任何地址。
    return 1;
    //如果用的new分配的內存需要用delete來釋放存儲空間
}

線性表是否爲空表

bool listempty(sqlist&l)
{
    return (l.length==0)?true:false;
}

線性表是否已滿

bool listfull(sqlist&l)
{
    return (l.length==l.listsize)?true:false;
}

獲取線性表當前元素的個數

int listlength(sqlist&l)
{
    return l.length;
}

獲得指定位置的數據元素

status getelem(sqlist&l,int i,elemtype&e)
{
    if(i<1||i>l.length)
        exit(0);
    e=*(l.elem+i-1);
    return 1;
}

返回前驅

int priorelem(sqlist&l,ElemType&e,Elemtype&ee)
{
    int i;
    for(i=1;i<=l.length;i++)
    {
        if(l.elem[i]==e&&i>1)
        {
            ee=l.elem[i-1];
            return 1;
        }
    }
    return 0;
}

線性表裏插入元素

status insertlist(sqlist&l,int i,ElemType e)
{
    int j;
    if(i<1||i>l.length)//i的值不合法
        return 0;
    if(l.length>=l.listsize)//當前存儲空間已經滿了
    {
        ElemType *newbase;
        newbase=(ElemType*)realloc((l.listsize+LISTINCREMENT)*sizeof(ElemType));
        if(!newbase)
            exit(0);
        l.elem=newbase;
        l.listsize=l.listsize+LISTINCREMENT;
    }
    for(j=i+1; j<=l.length; j++)
        l.elem[j]=l.elem[j-1];
    l.elem[i-1]=e;
    l.length++;
    return 1;
    //指針實現
    //for(p=&(l.elem[l.length-1]);p>=q;p--)
    //  *(p+1)=*p;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章