我认为是最简单的c++实现线性表中顺序表相关过程

来源:互联网 发布:美国海关进出口数据 编辑:程序博客网 时间:2024/06/03 15:51

每行代码都有详细注释:我认为这是我见过最简单的顺序表了,小白完全看的懂,大神勿喷

如果不会的给我留言

第一个是链表类:List.h

#pragma once
#ifndef LIST_H
#define LIST_H


class List
{
private:
int *arr;//存储数据的数组
int maxLength;//容器的最大容量
int size;//存储到线性表中的实际数据个数
public:
List(int size);//构造函数
~List();//析构函数
bool insertElement(int i, int *node);//插入数据
bool deleteElement(int i, int *node);//删除数据
void ListBL();//顺序表的遍历
bool getElement(int i, int *e);//根据下标获取指定元素
int LocateElement(int *e);//根据参数确定*e元素在顺序表中的下标
bool priorElem(int *currElem, int *preElem);//.获取指定元素的(前驱)
};
#endif // !LIST_H


实现:

#include"List.h"
#include<iostream>
using namespace std;


List::List(int len)//编写构造函数
{
arr = new int[len];//创建一个指定长度的数组
maxLength = len;//将参数设置为顺序表的最大长度
size = 0;//指定存储的元素个数设置为0
}
List::~List()
{
//清空顺序表
size = 0;
//让指针清除
delete arr;
//让指针指向空
arr = NULL;
}
bool List::insertElement(int i/*下标*/,int *p/*数据*/ )//向指定位置插入元素
{
//先判断下标是否合法
if (i < 0 || i > size)
{
return false;
}
//从后往前将数据往顺序表后移动一位
for (int k = size-1; k >= i; k--)
{
arr[k + 1] = arr[k];
}
//将参数的值存储到指定下标的位置
arr[i] = *p;
size++;
return true;
}
void List::ListBL()//顺序表的遍历
{
cout << "元素遍历如下:" << endl;
for (int k = 0; k < size; k++)
{
cout << arr[k] << "  ";
}
cout << endl;
}
bool List::deleteElement(int i, int *node)
{
if (i<0 || i>= size)//判断下标是否合法
{
return false;
}
*node = arr[i];//先将要被删除的数据保存到返回参数node中
for (int k = i + 1; k < size; k++)
{
arr[k - 1] = arr[k];
}
arr[size - 1] = NULL;
size--;
}


//根据下标获取指定元素 将数据保存到返回参数*e中
bool List::getElement(int i, int *p)
{
if (i<0 || i>=size)
{
return -1;
}
else
{
for (size_t j = 0; j < size; j++)
{
if (i == j)
{
p = &arr[j];
cout << "该元素的数据为:" << *p << endl;
break;
}
}
}
}
int List::LocateElement(int *e)//根据参数确定*e元素在顺序表中的下标
{
for (size_t j = 0; j < size; j++)
{
if (arr[j] == *e) {
cout << "该元素的下标为:" << j << endl;
break;
}
}
return 0;
}


//获取指定元素的(前驱),*currElem代表当前这个元素,将获取的数据保存到返回参数 *preElem中
bool List::priorElem(int *currElem, int *preElem)
{
for (size_t i = 0; i < size; i++)
{
if (arr[i] == *currElem)
{
preElem = &arr[i - 1];
cout << "该元素的前驱为:" << *preElem << endl;
break;
}
}
return true;
}


 测试:

#include"List.h"
#include<iostream>
using namespace std;
int main()
{
//创建线性表
List *p = new List(10);
//添加元素
int a = 6;
int b = 4;
int c = 10;
p->insertElement(0, &a);
p->insertElement(1, &b);
p->insertElement(2, &c);
p->insertElement(3, &c);
p->ListBL();
p->getElement(2,0);
p->LocateElement(&a);
p->priorElem(&b, 0);
delete p;//删除数据表
system("pause");
return 0;
}


vs2015完美运行