数据结构复习——顺序表的实现野史趣闻

2018-11-01 17:00:35

文件分为三个部分SeqList.h、SeqList.cpp、main.cpp

建议不熟悉的同学练习一下(干货.jpg)

SeqList.h

#pragma once

const int MaxSize = 10;

class SeqList {

public:

SeqList() { length = 0; };

SeqList(int a[], int length);

void Insert(int i,int value);

int Delete(int i);

int Locate(int i);

void PrintList();

private:

int data[MaxSize];

int length;

};

SeqList.cpp

#include<iostream>

using namespace std;

#include'SeqList.h'

//使用数组初始化

SeqList::SeqList(int a[], int length) {

if (length > MaxSize)

throw'数组长度大于顺序表最大长度';

for (int i = 0; i < length; i++){

data[i] = a[i];

}

this->length = length;

}

//在第 i 个位置插入值为 value 的元素

//思路:将原来第 i 个及后面的元素向后移动,插入

void SeqList::Insert(int i, int value){

if (i >= MaxSize)

throw'上溢';

if (i < 1)

throw'位置非法';

for (int j = length; j >= i; j--) {

data[j] = data[j - 1];

}

data[i - 1] = value;

length++;

}

//删除第 i 个元素

//思路:将 i + 1 个及以后的元素前移

int SeqList::Delete(int i) {

if (length == 0)

throw '下溢';

if (i<0 || i>length)

throw '位置非法';

int value = data[i - 1];

for (int j= i; j < length; j++){

data[j - 1] = data[j];

}

length--;

return value;

}

//查找第 i 个元素

int SeqList::Locate(int i) {

if (length == 0)

throw '下溢';

if (i<0 || i>length)

throw '位置非法';

return data[i - 1];

}

void SeqList::PrintList() {

for (int i = 0; i < length; i++){

cout << data[i] << ' ';

}

cout << endl;

}

main.cpp

#include<iostream>

using namespace std;

#include'SeqList.h'

int main() {

int a[] = { 1,2,3,4 };

SeqList list(a, 4);

cout << '顺序表原始顺序为:' << endl;

list.PrintList();

cout << '在第3个位置插入5:' << endl;

list.Insert(3, 5);

list.PrintList();

cout << '输出第2个元素:' << endl;

cout << list.Locate(2) << endl;

cout << '删除第4个元素:' << endl;

list.Delete(4);

list.PrintList();

system('pause');

return 0;

}

结果

本文作者:一本草稿本(今日头条)
热门推荐