2021-02-09

C++ language implementation sequence table


Advantages and disadvantages of sequential tables Advantages of sequential tables:

  • The elements in the table have continuity in the storage address, and the address of any element can be quickly obtained through the subscript directly to achieve fast random access.
  • Inserting or deleting elements at the end of the sequence table is very fast.

Disadvantages of sequence table:

  • Inserting or deleting elements at positions other than the end of the sequence table requires moving all elements behind the operation position, which is slower.
  • The sequence table has a fixed length and cannot be flexibly scaled.

Common mistakes
in using the sequence table When traversing the elements in the sequence table, if there is an operation to erase or insert elements in the middle, pay attention to the pointing of the element subscript will change.

Algorithm implementation
Header file:

#ifndef SQLIST_H
#define SQLIST_H

#include"Star.h"
#define ELEMENT_TYPE Star
#define ARR_SIZE 100

typedef struct {
    
    
	ELEMENT_TYPE* eleArr;  //基地址
	unsigned length;  //长度
	unsigned size;  //容量
}SqList;
//初始化顺序表:
bool initList(SqList& sqL, const unsigned& size);
//销毁顺序表:
bool destroyList(SqList& sqL);
//向顺序表尾部追加元素[时间复杂度为o(1)]:
bool push_back(SqList& sqL, const ELEMENT_TYPE& ele);
//擦除顺序表尾部元素(声明为内联函数)[时间复杂度为o(1)]:
inline bool pop_back(SqList& sqL)
{
    
    
	if (sqL.length == 0) return false;
	--sqL.length;
	return true;
}
//向指定位置插入元素[时间复杂度为o(n)]:
bool insert(SqList& sqL, const unsigned& pos, const ELEMENT_TYPE& ele);
//擦除指定位置的元素[时间复杂度为o(n)]:
bool erase(SqList& sqL, const unsigned& pos);


#endif // !SQLIST_H

CPP file:

#include "SqList.h"

bool initList(SqList& sqL, const unsigned& size)
{
    
    
	sqL.eleArr = new ELEMENT_TYPE[size];
	if (!sqL.eleArr) return false;  //若内存分配出错(堆溢出)
	sqL.length = 0;
	sqL.size = size;
	return true;
}

bool destroyList(SqList& sqL)
{
    
    
	if (!sqL.eleArr) return false;
	delete[] sqL.eleArr;
	sqL.eleArr = nullptr;
	sqL.length = 0;
	sqL.size = 0;
	return true;
}

bool push_back(SqList& sqL, const ELEMENT_TYPE& ele)
{
    
    
	if (sqL.length == sqL.size) return false;
	sqL.eleArr[sqL.length] = ele;
	++sqL.length;
	return true;
}

bool insert(SqList& sqL, const unsigned& pos, const ELEMENT_TYPE& ele)
{
    
    
	if (pos<0 || pos>sqL.length || sqL.length == sqL.size) return false;
	++sqL.length;
	for (auto i = sqL.length; i > pos; --i) {
    
    
		sqL.eleArr[i] = sqL.eleArr[i - 1];
	}
	sqL.eleArr[pos] = ele;
	return true;
}

bool erase(SqList& sqL, const unsigned& pos)
{
    
    
	if (pos >= sqL.length || pos < 0) return false;
	for (auto i = pos; i != sqL.length - 1; ++i) {
    
    
		sqL.eleArr[i] = sqL.eleArr[i + 1];
	}
	--sqL.length;
	return true;
}

``

Guess you like

Origin blog.csdn.net/weixin_48343353/article/details/113774155