顺序表(C++实现)

一 、顺序表的定义:

          零个或多个数据元素的有限序列。线性表是最基本、最简单也是最常用的数据结构。

二 、特点:

         顺序表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外,其它数据元素都是首尾相接的。除最后一个元素之外其他数据元素均有唯一的后继,除第一个元素外,其他数据元素均有唯一的前驱。

       数据元素的存储位置满足:LOC(ai)=LOC(a1)+(i-1)*l   (l表示每个元素需要占用的存储单元)

三 、抽象数据类型:

ADT List
{
   数据对象:
   数据关系:
   基本操作:
      //构造一个空的线性表
   InitList(&L) 
     //销毁线性表
     //初始条件:线性表L已存在  
   DestoryList(&L)  
     //清空线性表
   ClearList(&L)
     //判空
   ListEmpty(&L)
     //返回L中数据元素个数
   ListLength(&L)
     //返回L中第i个数据元素的值
   GetElem(L,i,&e)
     //插入
   ListInster(&L,i,e)
     //删除
   ListDelete(&L,i,&e)
     //遍历
   ListTraverse(L,visit())
}

四 、实现:

头文件:

#include<iostream>
using namespace std;

#define INVALID        oxff

#define LIST_INIT_SIZE 100

typedef int ElemType;

/*typedef struct
{
   ElemType *elem;
   int      length;
   int      listsize;
}SqList;*/


class SqList
{
public:
   SqList();
   ~SqList();
   bool InitList();
   bool Insert(int i,ElemType x);
   bool Delete(int i);
   bool PrintList();
   int  Get(int i);
   int  Length();
private:
   ElemType data[LIST_INIT_SIZE];
   int length;
};

 功能文件:

#include "head.h"

SqList::SqList()
{
	memset(data, INVALID, LIST_INIT_SIZE);
	length = 0;
}

SqList::~SqList()
{
	delete[]data;
	length = 0;
}

bool SqList::InitList(int *arr, int len)
{
	for (int i = 0; i < len; i++)
	{
		data[i] = arr[i];
	}
	length = len;
	return true;
}

bool SqList::PrintList()
{
	cout << "线性表元素为:" << endl;
	for (int i = 0; i < length; i++)
	{
		cout << data[i] << " ";
	}
	cout << endl;
	return true;
}

int  SqList::Length()
{
	return length;
}

int  SqList::Get(int i)
{
	if (i<0 || i>length)
	{
		return false;
	}
	return data[i];
}

bool SqList::Inster(int i, ElemType x)    //插入的过程中注意元素移动的方向。 
{
	if (i<0 || i>length)
	{
		return false;
	}
	for (int j = length; j >= i; j--)
	{
		data[j] = data[j - 1];
	}
	data[i - 1] = x;
	length++;
	return true;
}

bool SqList::Delete(int i)  
{
	if (i<0 || i>length)
	{
		return false;
	}
	for (int j = i - 1; j < length; j++)
	{
		data[j] = data[j + 1];
	}
	length--;
	return true;
}

主函数: 

#include "head.h"

int main()
{
	SqList list;

	int num;
	cin >> num;
	int *arr = new int[num];
	for (int i = 0; i < num; i++)
	{
		cin >> arr[i];
	}
	
	list.InitList(arr,num);
	list.PrintList();

	int i, x;
	cout << "请输入要插入元素位置和元素:";
	cin >>i>>x;
	list.Inster(i,x);
	list.PrintList();

	cout << "请输入要删除元素位置";
	cin >> i;
	list.Delete(i);
	list.PrintList();

	system("pause");
	return 0;
}

五:顺序表的优缺点:

优点:

  • 随机访问,查找速度快。
  • 存储空间相邻,易操作。

缺点:

  • 插入和删除速度慢,需要移动大量元素。
  • 如果顺序表很大,操作分繁琐。

 

 

//以上代码测试环境为VS2017
 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值