线性表的基本操作

来源:互联网 发布:淘宝客服打字要多快 编辑:程序博客网 时间:2024/04/30 05:55

借助数组来描述顺序表。除了用数组来存储线性表的元素之外,顺序表还应该有表示线性表的长度属性,所以用结构类型来定义顺序表类型。

#define  OK   1#define  ERROR   -1#define  MAX_SIZE  100typedef  int  Status ;typedef  int  ElemType ; typedef  struct  sqlist{   ElemType  Elem_array[MAX_SIZE] ;    int length ;} SqList ;

1 顺序线性表初始化

 Status Init_SqList( SqList *L ) {  L->elem_array=( ElemType * )malloc(MAX_SIZE*sizeof( ElemType ) ) ;if ( !L -> elem_array ) return  ERROR ; else {   L->length= 0 ;    return OK ;  }  }

2 顺序线性表的插入
在线性表 L= (a1,…a i-1,ai, ai+1,…,an) 中的第i(1≦i≦n)个位置上插入一个新结点e,使其成为线性表:
L=(a1,…a i-1,e,ai,ai+1,…,an)
实现步骤
(1) 将线性表L中的第i个至第n个结点后移一个位置。
(2) 将结点e插入到结点ai-1之后。
(3) 线性表长度加1。

算法描述

Status Insert_SqList(Sqlist *L,int i ,ElemType e) {   int j ;if  ( i<0||i>L->length-1)   return  ERROR ;if  (L->length>=MAX_SIZE){    printf(“线性表溢出!\n”);  return  ERROR ;  }for  ( j=L->length1; j>=i-1; --j )L->Elem_array[j+1]=L->Elem_array[j];/*  i-1位置以后的所有结点后移  */L->Elem_array[i-1]=e;    /*  在i-1位置插入结点  */L->length++ ;return  OK ;  }

3 顺序线性表的删除
在线性表 L=(a1,…a i-1,ai, ai+1,…,an) 中删除结点ai(1≦i≦n),使其成为线性表:
L= (a1,…ai-1,ai+1,…,an)
实现步骤
(1) 将线性表L中的第i+1个至第n个结点依此向前移动一个位置。
(2) 线性表长度减1。
算法描述

ElemType  Delete_SqList(Sqlist *Lint i){  int  k ;   ElemType  x ;if  (L->length==0){  printf(“线性表L为空!\n”); return ERROR;  } else if ( i<1||i>L->length ) {  printf(“要删除的数据元素不存在!\n”) ; return ERROR ; }else  {  x=L->Elem_array[i-1] ;   /*保存结点的值*/for ( k=i ;  k<L->length ; k++)       L->Elem_array[k-1]=L->Elem_array[k];             /*  i位置以后的所有结点前移  */L->length--;  return (x);}} 

4 顺序线性表的查找定位删除
在线性表 L= (a1,a2,…,an) 中删除值为x的第一个结点。
实现步骤
(1) 在线性表L查找值为x的第一个数据元素。
(2) 将从找到的位置至最后一个结点依次向前移动一个位置。
(3) 线性表长度减1。
算法描述

Status  Locate_Delete_SqList(Sqlist *L,ElemType x)     /*  删除线性表L中值为x的第一个结点  */{  int  i=0 , k ;while  (i<L->length)      /*查找值为x的第一个结点*/{   if  (L->Elem_array[i]!=x )  i++ ; else     {  for ( k=i+1; k< L->length; k++)           L->Elem_array[k-1]=L->Elem_array[k];        L->length--;  break ;    }}if  (i>L->length){    printf(“要删除的数据元素不存在!\n”) ; return ERROR ;  }return  OK;    } 

完整程序会在下一篇博客中给出。

0 0
原创粉丝点击