顺序表

来源:互联网 发布:淘宝客优惠券口令推广 编辑:程序博客网 时间:2024/06/01 23:51
#include<iostream>#include<cstdio>#include<stdlib.h>#include<malloc.h>#define LIST_INIT_SIZE 10//线性表初始长度 #define LISTINCREMENT 10//增量 #define TRUE 1#define FALSE 0#define OK 1#define ERROR 0#define INFEASIBLE -1#define OVERFLOW -2using namespace std;typedef int ElemType;//设置线性表中存放的数据类型 typedef int Status;typedef struct{    ElemType* elem;//存储空间的基址     int length;//线性表的长度     int listSize;//线性表的存储容量 }sqList;Status initList_Sq(sqList&L){    L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));    if(!L.elem)exit(OVERFLOW);    L.length=0;    L.listSize=LIST_INIT_SIZE;    return OK;}//将元素插入到第i个元素前面 Status listInsert(sqList&L,int i,ElemType e){    if(i<1||i>L.length+1)return ERROR;    if(L.length>=L.listSize){        //当存储容量不够的时候,进行扩容         ElemType*newBase=(ElemType*)realloc(L.elem,(LISTINCREMENT+LIST_INIT_SIZE)*sizeof(ElemType));        if(!newBase)exit(OVERFLOW);        L.elem=newBase;        L.listSize=L.listSize+LISTINCREMENT;    }    //[i-1,L.length-1]全部后移一个单元     for(int k=L.length-1;k>=i-1;k--){        L.elem[k+1]=L.elem[k];    }    L.elem[i-1]=e;    L.length++;    return OK;}//在顺序表中删除第i个元素,并且返回用e返回删除元素的值 Status listDelete(sqList&L,int i,ElemType&e){    if(i<1||i>L.length)return ERROR;    e=L.elem[i-1];    for(int k=i;k<L.length;k++){        L.elem[k-1]=L.elem[k];    }    L.length--;    return OK; }int locate_Sq(sqList L,ElemType e,Status(*compare)(ElemType,ElemType)){    //在顺序线性表中查找第一个值与e相等,相等规则在compare中    for(int i=0;i<L.length;i++){        if((*compare)(L.elem[i],e))return i+1;    }    return -1;//没有找到 }Status compare(ElemType e1,ElemType e2){    if(e1==e2)return TRUE;    return FALSE;} int main(){    return 0;} 
原创粉丝点击