设为首页 加入收藏

TOP

数据结构--关于线性表插入元素
2012-12-06 13:53:06 来源: 作者: 【 】 浏览:276
Tags:数据结构 关于 线性 插入 元素

  #include <iostream>

  using namespace std;

  #define LIST_INIT_SIZE 100 //初始化分配量

  #define LISTINCREMENT 10 //存储空间的分配增量

  typedef int Status;

  typedef int ElemType;

  typedef struct{

  ElemType *elem;//储存空间基址

  int length;//当前长度

  int listsize;//当前的分配的存储容量 (以sizeof (ElemType)为单位)

  }SqList;

  Status InitList_sq(SqList &L){

  L.elem = (ElemType *)malloc(LIST_INIT_SIZE *sizeof(ElemType));

  if ( !L.elem)exit(1);//存储分配失败

  L.length = 0; //空表长度为0

  L.listsize =LIST_INIT_SIZE;//初始储存容量

  return true;

  }

  Status ListInsert_Sq(SqList &L,int i,ElemType e)

  {

  //在顺序线性表L中第i个位置之前插入新的元素e

  //i的合法值为1<=i<=ListLength_Sq(L)+1

  if(i <1 || i> L.length + 1)

  return false;   //i值不合法

  if(L.length >= L.listsize)   //当前存储空间已满,增加分配

  {

  ElemType *newbase = (ElemType *)realloc(L.elem,(L.listsize + LISTINCREMENT )* sizeof(ElemType));

  if(!newbase)

  exit(1);    //存储分配失败

  L.elem = newbase;//新基址

  L.listsize += LISTINCREMENT;    //增加存储容量

  }

  ElemType *q = &(L.elem[i-1]);//q为插入位置

  for(ElemType *p = &(L.elem[L.length-1]);p>=q;--p)

  *(p+1) = *p;    //插入位置及之后的元素右移

  *q = e;     //插入e

  ++L.length;     //表长增1

  return true;

  }

  int main()

  {

  SqList L;

  InitList_sq(L);

  ListInsert_Sq(L,1,2);

  return 0;

  }

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C语言中数据结构小练习 下一篇数据结构——KMP算法C++版

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: