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

该博客详细介绍了如何使用C++实现顺序存储的线性表,包括SqList.h头文件,初始化列表的InitList.h文件,以及列表插入操作的ListInsert.h文件。
摘要由CSDN通过智能技术生成

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上调试成功。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值