您的位置:首页 > 理论基础 > 数据结构算法

数据结构--线性表 算法函数的实现(实现线性表的插入操作)

2018-03-15 18:23 471 查看
/*
文件名称:实现线性表的插入操作
*/
#include <iostream>
using namespace std;
#define LIST_INIT_SIZE    100   //线性表存储空间的初始分配量
#define LISTINCREMENT   10  //线性表存储空间的分配增量
typedef int ElemType;      //定义别名
typedef int Status;      //定义别名

typedef struct {
ElemType *elem;     //存储空间基址
int length;     //当前长度
int listsize;       //当前分配的存储容量(以sizeof(ElemType)为单位)
}SqList;

Status InitList_Sq(SqList &L) {
//构造一个空的线性表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;
}

void main()
{
SqList L;
InitList_Sq(L);
ListInsert_Sq(L, 1, 2);
return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐