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

线性表的顺序储存结构定义(动态)实现

2017-02-01 13:28 483 查看

代码示例:

/*
function:线性表的顺序储存结构定义(动态)实现线性表的初始化、插入、删除和显示功能
created by: xilong
date: 2017.2.1
*/

#include "iostream"
using namespace std;
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define LIST_INIT_SIZE 20  //线性表存储空间的初始分配量
#define OVERFLOW -2
#define LISTINCREMENT 10  //线性表存储空间的分配增量

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

/*
初始化操作,构造空的线性表L
*/
Status initList(SqList *L)
{
L->data = (int *)malloc(LIST_INIT_SIZE * sizeof(int));
if (!L->data) exit(OVERFLOW); //存储分配失败
L->length = 0;
L->listsize = LIST_INIT_SIZE;
return OK;
}

// 遍历线性表
Status listTraverse(SqList *L){
int i;
for (i = 0; i < L->length; i++){
printf("%d ", L->data[i]);
}
printf("\n");
return OK;
}

// 释放资源
void free(SqList *L)
{
free(L->data);
L->length = 0;

}

/*
在线性表中第i个元素位置上,插入一个指针e所指的元素
*/
Status listInsert(SqList *L, int i, ElemType e)
{
if (i < 1 || i> L->length + 1)
{
return ERROR; // 输入不合法
}
if (L->length <= LIST_INIT_SIZE)
{
ElemType *newnode = (int *)realloc(L->data,(LISTINCREMENT + LIST_INIT_SIZE) * sizeof(int));
if (!newnode) exit(OVERFLOW);
L->data = newnode;
L->listsize += LISTINCREMENT;
}
ElemType *p = &(L->data[i - 1]); // 待插入元素的位置,指针 p 指向待插入元素的位置
ElemType *q;
for (q = &(L->data[L->length - 1]); q >= p; --q){
*(q + 1) = *q;  // 从待插入元素的位置开始,将指针向后移动一位
}
*p = e; // 插入元素
++L->length;
}

/*
删除指定位置的元素
*/
Status listDelete(SqList *L, int i, ElemType &e)
{
if (i < 1 || i > L->length)
{
return ERROR;
}
ElemType* p = &(L->data[i - 1]); // 待删除元素位置
e = *p;
//ElemType* q = L->data + L->length - 1;
for (; p < &(L->data[L->length - 1]); p++){ // 从p(不包含p)后面的元素开始依次向前移一位
* p = *(p + 1);
}
L->length--;
return OK;
}

void main()
{
SqList L;
ElemType e;
initList(&L);
cout << "初始化成功!"<< endl;
cout << "开始插入............................................." << endl;
listInsert(&L, 1, 10);
listInsert(&L, 2, 20);
listInsert(&L, 3, 30);
listInsert(&L, 4, 40);
listInsert(&L, 5, 50);
listInsert(&L, 2, 60);
cout << "插入完毕!" << endl;
cout << "打印线性表中的所有数据:";
listTraverse(&L);
cout << "开始删除............................................" << endl;
listDelete(&L, 3, e);
listDelete(&L, 5, e);
cout << "删除成功!" << endl;
cout << "删除后打印线性表中的所有数据:";
listTraverse(&L);
cout << "释放内存............................................" << endl;
free(&L);
cout << "释放内存完成!" << endl;
system("pause");
}


程序截图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线性表 数据结构 c++