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

数据结构——线性表——顺序存储结构——C++实现线性表

2017-05-12 10:02 459 查看
顺序存储结构C++实现篇:主要实现了线性表的定义、初始化、显示、增、删结点操作。

切记亲力亲为,动手实践写代码

main.cpp

/***************************************************************************
*  @file       main.cpp
*  @author     MISAYAONE
*  @date       11  May 2017
*  @remark     11  May 2017
*  @theme      Sequence List
***************************************************************************/

#include "Linear_list.h"

#include <iostream>
using namespace std;

int main(int argc, char** argv)
{
Seque_list L;
Init_list(L);
List_dispaly(L);

Insertion(L,56,3);
cout<<endl;
cout<<"插入结点后:"<<endl;
List_dispaly(L);

Delete(L,2);
cout<<endl;
cout<<"删除结点后:"<<endl;
List_dispaly(L);

system("pause");
return 0;
}


Linear_list.h

//线性表数据结构的定义
#define MAXSIZE 1024
typedef struct
{
int data[MAXSIZE]; //存放线性表结点的数据空间
int length;        //指示线性表当前长度
} Seque_list;

//线性表的初始化
bool Init_list(Seque_list &L);

//显示线性表的内容
bool List_dispaly(Seque_list L);

//线性表的插入操作
bool Insertion(Seque_list &L,int x,int i);

//线性表的删除操作
bool Delete(Seque_list &L,int i);


Linear_list.cpp

#include "Linear_list.h"
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

bool Init_list(Seque_list &L)  //传入线性表的引用或者指针,否则不能改变
{
L.length = 0;             //初始化当前线性表长度
int List_data,i = 0;
while (cin>>List_data)
{
L.data[i] = List_data;
++(L.length);
++i;
}
return true;
}

bool List_dispaly(Seque_list L)
{
cout<<"线性表的大小为:"<<L.length<<endl;
cout<<"线性表的数据元素为:"<<" ";
for (int i = 0; i < L.length; ++i)
{
cout<<L.data[i]<<" ";
}
return true;
}

//三个参数,讲结点为x的数据插入到线性表L的位置i上
bool Insertion(Seque_list &L,int x,int i)
{
if (i >= MAXSIZE || L.length>=MAXSIZE-1) //加上溢出判断
{
return false;
}
else
{
if (i<0 || i>=L.length)               //加上非法位置判断
{
cout<<"插入位置非法"<<endl;
return false;
}
else
{
for (int j = L.length;j > i;j--)
{
L.data[j] = L.data[j-1];
}
L.data[i] = x;
L.length +=1;     //修改插入元素后的线性表大小
}
}
}

bool Delete(Seque_list &L,int i)
{
if (i<0 || i>=L.length)   //非法位置判断
{
return false;
}
else
{
for (int j = i; j<L.length; j++)
{
L.data[j] = L.data[j+1];
}
L.length -= 1;        //修改插入元素后的线性表大小
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息