您的位置:首页 > 编程语言 > C语言/C++

C++实现顺序存储的线性表

2016-04-07 14:24 393 查看

1、SqList.h

#ifndef SQLIST_H
#define  SQLIST_H

#define MAXSIZE 20		// 存储空间初始分配量
typedef int ElemType;	// ElemType类型根据实际情况而定,这里假设为 int
typedef struct
{
ElemType data[MAXSIZE];		// 数组存储数据元素,最大值为MAXSIZE
int length;					// 线性表当前长度
}SqList;

#endif


2、InitList.h

#ifndef INITLIST_H
#define INITLIST_H

#include "SqList.h"
#include "GetElem.h"

// 初始化操作,建立一个空的线性表L
Status InitList(SqList *L)
{
L->length = 0;
return OK;
}

#endif


3、ListInsert.h

#ifndef LISTINSERT_H
#define LISTINSERT_H

#include "SqList.h"
#include "GetElem.h"

// 初始条件 : 顺序呢线性表 L 已存在, 1 <= i <= ListLength(L)
// 操作结果 : 在 L 中第 i 个位置之前插入新的数据元素 e, L 的长度加 1
Status ListInsert(SqList *L, int i, ElemType e)
{
int k;
if (L->length == MAXSIZE)		// 顺序线性表已满
return ERROR;
if (i < 1 || i > L->length + 1)	// 当 i 不在范围内时
return ERROR;
if (i <= L->length)			// 若插入数据位置不在表尾
{
for (k = L->length - 1; k >= i - 1; k--)	// 将要插入位置后数据元素向后移动一位
L->data[k+1] = L->data[k];
}
L->data[i-1] = e;		// 将新元素插入
L->length++;
return OK;
}

#endif


4、ListDelete.h
#ifndef LISTDELETE_H
#define LISTDELETE_H

#include "SqList.h"
#include "GetElem.h"

// 初始条件 : 顺序线性表 L 已存在, 1 <= i <= ListLength(L)
// 操作结果 : 删除 L 的第 i 个数据元素, 并用 e 返回其值, L的长度减 1
Status ListDelete(SqList *L, int i, ElemType *e)
{
int k;
if (L->length == 0)		// 线性表为空
return ERROR;
if (i < 1 || i > L->length)		// 删除位置不正确
return ERROR;
*e = L->data[i-1];
if (i < L->length)		// 如果删除不是最后位置
{
for (k = i; k < L->length; k++)
L->data[i] = L->data[i+1];
}
L->length--;
return OK;
}

#endif


5、GetElem.h
#ifndef GETELEM_H
#define GETELEM_H

#include "SqList.h"
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
// Status 是函数的类型,其值是函数结果状态代码,如 OK 等
// 初始条件 : 顺序线性表 L 已经存在, 1 <= i <= ListLength(L)
// 操作结果 : 用 e 返回 L 中第 i 个数据元素的值

Status GetElem(SqList L, int i, ElemType *e)
{
if(L.length == 0 || i < 1 || i > L.length)
return ERROR;
*e = L.data[i-1];
return OK;
}

#endif


6、Source.cpp
#include "GetElem.h"
#include "ListDelete.h"
#include "ListInsert.h"
#include "SqList.h"
#include "InitList.h"
#include <iostream>
using namespace std;

int main()
{
SqList L;
InitList(&L);		// 初始化顺序表L
ElemType e;
for (int i = 1; i < 10; i++)
{
e = rand();		// 通过rand()函数生成一个随机数赋值给e
ListInsert(&L, i, e);		// 将生成的随机数插入到顺序表的表尾
cout <<e << "  ";
}
cout <<endl;
ElemType ele;
// 输出线性表L中的所有元素
for (int i = 1; i < L.length + 1; i++)
{
GetElem(L, i, &ele);
printf("%d  ", ele);
}
system("pause");
return 0;
}


源码在Visual Studio2012上调试成功。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: