数据结构

来源:互联网 发布:nba2k16捏脸吴亦凡数据 编辑:程序博客网 时间:2024/06/03 20:01

线性表

#include <stdio.h>#include <stdlib.h>typedef int Elemtype;#define error 0#define ok 1#define MAX 20#define LISTNEWCREATE 10typedef int status;

一,定义
通常用数组来描述,由于线性表长度可变,故使用C语言的动态分配实现。

//定义typedef int Elemtype;typedef struct{    Elemtype *e;//指向线性表的基地址    int length;//线性表当前长度    int list_size;//当前分配空间大小}SqList;

二,创建空表

/*------构造一个空表------*/status Create_list(SqList *L){    L->list_size=MAX;    L->e=(Elemtype*)malloc(sizeof(Elemtype)*L->list_size);//e指向连续list_size 个Elemtype类型的数据。相当于Elemtype data[list_size];    if(L->e==NULL)    {        printf("faliure\n");        return error;    }    printf("success\n");    L->length=0;    return ok;}

三。线性表的插入
由于线性表的下标从1开始,而定义的数组则是从0开始。
pos=i;即在i位置之前插入元素,则i,及其后面都要向后平移一位。

/*---------线性表插入-----*/status Insert_list(SqList *L,int pos ,Elemtype e){    int i;    if(!(L->e))//判断表是否存在    {        printf("list doesn't exit\n");        return error;    }    if(pos<1 ||pos>L->length+1)//判断插入位置是否合法    {        printf("pos is wrong \n");        return error;    }    if(L->length>=L->list_size)//当前存储空间已满,增加分配    {         Elemtype *newbase=(Elemtype*)realloc(L->e,(L->list_size+LISTNEWCREATE)*sizeof(Elemtype));        if(!newbase)        return error;        L->e=newbase;        L->listsize+=LISTNEWCREATE;    }    for(i=L->length-1;i>=pos-1;i--){        L->e[++i]=L->e[i];    }/*法二:    Elemtype *p,*q;    q=&(L->e[pos-1]);    for( p=&(L->e[length-1]);p>=q;p--){        *(p+1)=*p;    }    */    L->e[++i]=e;    ++L->length;    return ok;}

??realloc 的使用
四,删除操作

/*---------线性表删除-----*/status Del_list(SqList *L,int pos){    if(!(L->e))    {        printf("list doesn't exit \n");        return error;    }    if(L->length==0)    {        printf("list is empty\n");        return error;    }    if(pos<1 || pos>L->length)    {        printf("pos is wrong\n");        return error;    }    Elemtype *p,*q;    p=&(L->e[pos-1]);    for(q=&(L->e[L->length-1]);q>p;q--){       *(--q)=*q;    }    L->length--;    return ok;}

五.获取某一位置的线性表的值

/*--------获取第i个元素----*/status Get_Elem(SqList *L,int pos ,Elemtype *e){    if(!(L->e))    {        printf("list doesn't exit\n");        return error;    }    if(pos<1 ||pos>L->length)    {        printf("pos is wrong:\n");        return error;    }    *e=L->e[pos-1];//指向指针后pos个单位可以这样实现!    /*    pos--;    while(pos--){        L->e++;    }    *e=*(L->e);       */}

六。寻找线性表中第一个与e的值相等的序号

status LocateElem(SqList L,ElemType e,int (*compare)(ElemType,ElemType))   {    //返回顺序线性表L中第1个满足compare()的数据元素的位序        if(!L.elem){printf("线性表不存在!!\n"); return ERROR;}       int i=1;       ElemType *p = L.elem;       while(i <= L.length && !(*compare)(*p++,e)) ++i;       if(i <= L.length) return i;       else return 0;   }
0 0
原创粉丝点击