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

C++数据结构之线性顺序表基本操作

2015-04-25 20:08 627 查看
线性表的顺序存储结构的优缺点:

优点:无须为表示表中元素之间的逻辑关系而增加额外的存储空间;可以快速地存取表中任一位置的元素O(1)

缺 点:插入和删除操作需要移动大量元素O(n);当线性表长度变化较大时,难以确定存储空间的容量;造成存储空间的“碎片 ”

#include <iostream>

using namespace std;

#define MAX_SIZE 20

typedef int ElemType;

typedef struct

{

ElemType data[MAX_SIZE];

int length;

}SqList;

/*初始化顺序表*/

bool SqListInit(SqList &Sq)

{

for (int i = 0; i < MAX_SIZE; i++)

{

Sq.data[i] = 0;

}

Sq.length = 0;

return true;

}

/*判断表是否为空*/

bool isSqListEmpty(SqList Sq)

{

if (Sq.length == 0)

return true;

return false;

}

/*清空表*/

void clearSqList(SqList &Sq)

{

for (int i = 0; i < Sq.length; i++)

{

Sq.data[i] = 0;

}

Sq.length = 0;

}

/*用ptr返回Sq中第pos个数据元素的值,注意pos是指位置,第一个位置的数组是从0开始的*/

bool getElement(SqList Sq, int pos, ElemType *ptr)

{

if (Sq.length == 0 || pos < 1 || pos > Sq.length)

return false;

*ptr = Sq.data[pos - 1];

return true;

}

/*返回Sq中第一个与Elem相等的数据元素的位序,若不存在则返回0*/

int Locate(SqList Sq, ElemType elem)

{

for (int i = 0; i < Sq.length; i++)

{

if (Sq.data[i] == elem)

{

return i + 1;

}

}

return 0;

}

/*在Sq中第pos个位置之前插入新的数据元素Elem,Sq的长度加1*/

bool SqListInsert(SqList &Sq, int pos, ElemType elem)

{

if (Sq.length == MAX_SIZE)

return false;

if (pos < 1 || pos > Sq.length + 1)

return false;

for (int i = Sq.length - 1; i >= pos - 1; i--)

{

Sq.data[i + 1] = Sq.data[i];

}

Sq.data[pos - 1] = elem;

Sq.length++;

return true;

}

/*删除Sq的第pos个数据元素,并用delete返回其值,Sq的长度减1*/

bool SqListDelete(SqList &Sq, int pos, ElemType* pe)

{

if (Sq.length == 0)

return false;

if (pos < 1 || pos > Sq.length + 1)

return false;

*pe = Sq.data[pos - 1];

for (int i = pos - 1; i <= Sq.length - 1; i++)

{

Sq.data[i] = Sq.data[i + 1];

}

Sq.length--;

return true;

}

/*返回顺序表的长度*/

int SqListLength(SqList Sq)

{

return Sq.length;

}

/*将所有在线性表Pb但不在Pa中的元素都插入到Pa中*/

void MergeSqList(SqList &Pa, SqList &Pb)

{

int pa_length = Pa.length;

int pb_length = Pb.length;

ElemType temp;

for (int i = 0; i < pb_length; i++)

{

if (getElement(Pb, i + 1, &temp))

{

if (Locate(Pa, temp) == 0)

SqListInsert(Pa, ++pa_length, temp); //将Pa中不存在的元素从Pb插入到Pa的表尾

}

}

}

int main(void)

{

SqList Sq;

SqListInit(Sq);

for (int i = 0; i < 5; i++)

SqListInsert(Sq, i, i);

if (!isSqListEmpty(Sq))

{

cout << "Sq:" << endl;

for (int i = 0; i < Sq.length; i++)

cout << Sq.data[i] << " " ;

}

cout << endl;

int pos = Locate(Sq, 2);

int pe;

SqListDelete(Sq, pos, &pe);

cout << "Sq:" << endl;

for (int i = 0; i < Sq.length; i++)

cout << Sq.data[i] << " ";

cout << endl;

SqList Sqq;

SqListInit(Sqq);

for (int i = 0; i < 5; i++)

SqListInsert(Sqq, i, i);

if (Sqq.length != 0)

{

cout << "Sqq:" << endl;

for (int i = 0; i < Sqq.length; i++)

cout << Sqq.data[i] << " " ;

}

cout << endl;

MergeSqList(Sq, Sqq);

cout << "After Merge Sq:" << endl;

for (int i = 0; i < Sq.length; i++)

cout << Sq.data[i] << " ";

cout << endl;

}






内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐