最近学习了数据结构,在这几天主要学习了线性表。它的定义如下:线性表是最基本、最简单、也是最常用的一种数据结构。线性表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外,其它数据元素都是首尾相接的。线性表的逻辑结构简单,便于实现和操作。在这里写了线性表的初始化,赋值,删除等操作。具体的会再补充。
#include "stdio.h"
#include "malloc.h"
#include "stdlib.h"
# define LIST_INIT_SIZE 100
# define LISTINCREMENT 10
# define TRUE 1
# define FALSE 0
# define OK 1
# define ERROR 0
# define INFEASIBLE -1
# define OVERFLOW -2
typedef int Status;
typedef int ElemType;
//定义线性表的相关属性
typedef struct {
ElemType * elem;//列表的地址
int length ; // 表长,初始为 0
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 Insert_sq(SqList *L,int i ,ElemType e){
int *newbase,*q,*p ;
//对于插入的i位置进行判定
if(i<1||i>L->length) return ERROR ;
//如果分配空间不足,重新添加分配空间
if(L->length>=L->listsize){
newbase = (ElemType*)realloc(L->elem,(L->listsize+ LISTINCREMENT)*(LISTINCREMENT));
if(!newbase) exit(OVERFLOW) ;//分配失败
L->elem = newbase;
L->listsize += LISTINCREMENT ;
}
//进行表中的元素后移
q = &(L->elem[i-1]);
for(p = &(L->elem[L->length-1]);p>=q;--p)
*(p+1)= * p ;
//插入e的值
*q = e ;//赋值
++L->length;//表长加1
return OK;
}
//获取线性表I位的数值,返回到e中
Status GetElem(SqList *L,int i ,ElemType e){
//判断i的值是否合法
int a ;
if((i<1)||(i>L->length+1)) return ERROR ;
for( a= 0 ;a<L->length-1;a++){
if(a==i){
e = L->elem[a] ;
break;
}
}
return e ;
}
//删除
Status Delete(SqList *L,int i ,ElemType e){
ElemType *p,*q;
if((i<1)||(i>L->length+1)) return ERROR ;
e = L->elem[i-1] ; //把删除的i的值赋给e
p = &(L->elem[i-1]);//i为的地址
q = (L->elem) +(L->length-1) ;//表尾的位置
//被删除的元素之后的元素右移
for(++p;p<=q;++p)
*(p-1) = *p;
--L->length;//表长减1
return OK;
}
int main()
{
Status InitList_Sq ( SqList *L );
SqList L;
int j=1;
int i;
int a ;
InitList_Sq ( &L );
//对表进行赋值
for(i=1;i<=6;i++){
scanf("%d",&L.elem[i-1]);
++L.length;
}
//输出表中的值
for(j=1;j<=6;j++)
printf("%d",L.elem[j-1]);
}