数据结构之顺序线性表

数据结构之顺序表

理解

  • 以数组的形式构造顺序线性表
  • 相邻元素之间有物理联系(地址有关系)
  • 与链式表相比,删除、插入比较麻烦
  • 与链式表相比,查找位置的元素的话很快,查找元素的位置一样都得循环
  • 可以从末尾向前循环,也能从任一位置开始向前向后循环

代码

#include <stdio.h>
#include <stdlib.h> 
#define MAXSIDE 100     /*定义MAXSIDE值,线性表的大小*/ 
typedef int ElementType; /*定义元素类型 int double 等*/
typedef int Position;
typedef struct LNode *List;
struct LNode {
	ElementType Data[MAXSIDE];
	Position Last;
};

/* 初始化 */
List MakeEmpty()
{
	List L;
	
	L = (List)malloc(sizeof(struct LNode));
	L->Last = -1;
	
	return L;
} 

/* 查找 */
#define ERROR -1

Position Find( List L, ElementType X )
{
	Position i = 0;
	while( i <= L->Last && L->Data[i]!= X )
		i++;
	if ( i > L->Last ) return ERROR; /* 如果没找到,返回错误信息*/
	else return i;
} 

/* 插入 */
bool Insert( List L, ElementType X, Position P )
{
	Position i;
	
	if ( L->Last == MAXSIDE-1){
		/* 说明空间已满,不能再插入*/
		printf("线性表已满");
		return false;
	} 
	if ( P<0 || P>L->Last+1 ){
		printf("位置不合法");
		/* 插入给的位置P有问题*/
		return false; 
	}
	/* 将顺序线性表的位置P后的元素向后移(从最后一个元素开始)*/
	for( i=L->Last; i>=P; i--)
		L->Data[i+1] = L->Data[i];
	L->Data[P] = X;
	L->Last++;		/* 表的末位置加一 */
	return true; 
}

/*  删除 */
bool Delete( List L, Position P )
{
	Position i;
	
	if( P<0 || P>L->Last ){
		printf("位置%d不存在元素",P);
		return false;
	}
	/* 将顺序线性表P位置后的每个元素向前移(从P+1位置开始)*/ 
	for( i=P+1; i<=L->Last; i++)
		L->Data[i-1] = L->Data[i];
	L->Last--;
	return true;
}
posted @ 2018-04-20 20:49  Tanglement  阅读(192)  评论(0编辑  收藏  举报