数据结构与算法(C语言描述)——顺序表

来源:互联网 发布:查看当前进程 linux 编辑:程序博客网 时间:2024/05/16 15:12
/* 顺序表的存储结构及其基本运算 */
#include<stdio.h>
#include<stdlib.h>

#define OK 1  /* 函数结果状态代码 */
#define ERROR 0  /* 函数结果状态代码 */
#define LIST_INIT_SIZE 100  /* 初始化空间 */ 
#define LISTINCREMENT 10  /* 增量 */

typedef int Status;  /* 函数类型,其值是函数结果状态代码 */
typedef int ElemType; /* 顺序表的数据类型 */

typedef struct SqList
{
 ElemType *elem;  /* 存储空间地址 */
 int length;   /* 当前长度 */
 int listsize;  /* 容量 */
}SqList;

/* 构造一个空的线性表 */
Status InitList(SqList *L)
{
 L->elem = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
 if(!L->elem) /* 存储空间分配失败 */
  return ERROR;
 L->length = 0;
 L->listsize = LIST_INIT_SIZE;
 return OK;
}

/* 判断表格是否为空 */
Status ListEmpty(SqList *L)
{
 return L->length == 0;
}

/* 查找postion处的值,并赋值给e */
Status GetElem(SqList L,int position,ElemType *e)
{
 if(position < 1 || position > L.length)
  return ERROR;
 *e = L.elem[position-1];
 return OK;
}

/* 查找第一个值域和e相等的元素的逻辑序位 */
int locateElem(SqList L,ElemType e)
{
 int position;
 for(position=0;position<L.length &&L.elem[position]!=e;position++);
 if(position = L.length)
  return 0;
 return ++position;
}

/* 打印顺序表 */
void ListDisplay(SqList L)
{
 int j;
 for(j=0;j<L.length;j++)
  printf("%d\t",L.elem[j]); 
}

/* 在position处插入新元素 */
Status ListInsert(SqList *L,int position,ElemType e)
{
 /* position不合法 */
 if(position < 1 || position > L->length+1)
  return ERROR;

 /* 当前长度大于等于表的分配空间,增加分配 */
 if(L->length >= L->listsize)
 {
   ElemType* newbase = (ElemType*)realloc(L->elem,
    (LIST_INIT_SIZE+LISTINCREMENT)*sizeof(ElemType));
   if(!newbase)
    return ERROR;
   L->elem = newbase;
   L->listsize += LISTINCREMENT;
 }
 
 /* position后面的元素整体后移,然后在position处插入新元素 */
 int i=L->length;
 if(position <= L->length)
 {
  for(;i>=position;i--)
   L->elem[i] = L->elem[i-1];
 }
 L->elem[i] = e;
 L->length++;
 return OK;
}

/* 删除position处元素,并将值赋予e */
Status ListDelete(SqList *L,int position,ElemType *e)
{
 /* 不合法位置 */
 if(position < 1 || position > L->length+1)
  return ERROR;
 
 *e = L->elem[position-1] ;
 int k;
 for(k= position-1;k<L->length-1; k++)
  L->elem[k] = L->elem[k+1];
 L->length--;
 return OK;
}


1 0