【数据结构】顺序表

前端之家收集整理的这篇文章主要介绍了【数据结构】顺序表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

学习数据结构基础,如有错误,请指正


/***
数据结构:顺序表的模拟
***/

#ifndef __sqlIST_H__ 
#define __sqlIST_H__

typedef int ElemType;
#define MAXSIZE 100
#define ADDSIZE 100

class sqlist
{
private:
	ElemType *elem;
	int longth;
	int size;
public:	
	sqlist();
	~sqlist();

	void initsqlist();
	void insertsqlist(int index,ElemType elem);
	void deletesqlist(int index);
	void print();
};

#endif // __sqlIST_H__



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

sqlist::sqlist()
{
	this->initsqlist();
}
sqlist::~sqlist()
{
	delete []this->elem;
}

void sqlist::initsqlist()
{
	//this->elem = (ElemType *) malloc( MAXSIZE * sizeof(ElemType) );  // C style
	this->elem = (ElemType *) new ElemType(MAXSIZE);  // C++ styles
	this->size = MAXSIZE;
	this->longth = 0;
}

void sqlist::insertsqlist(int index,ElemType elem)
{
	if (index<1 || index >longth+1)
	{
		exit(0);
	}

	if (this->longth>=this->size)
	{
		this->elem = (ElemType *)realloc(this->elem,(this->size+ADDSIZE)*sizeof(ElemType));
		this->size += ADDSIZE;
	}

	ElemType *p_insert;
	p_insert = &(this->elem[index-1]);

	ElemType *p;
	for( p=&(this->elem[(this->longth-1)]); p>=p_insert; --p )
	{
		*(p+1) = *p;
	}
	*p_insert = elem;
	++this->longth;

}

void sqlist::deletesqlist(int index)
{
	if (index<0 || index>this->longth)
	{
		exit(0);
	}

	for (ElemType *p=&(this->elem[index-1]);p!=&(this->elem[longth-1]);++p)
	{
		*p = *(p+1);
	}
	--this->longth;
}

void sqlist::print()
{
	cout<<"the list items:"<<endl;
	for (int i=0;i!=this->longth;++i)
	{		
		cout<<this->elem[i]<<endl;
	}
}

int main()
{
	sqlist *L = new sqlist();
	L->insertsqlist(1,1);
	L->insertsqlist(2,2);
	L->insertsqlist(3,3);
	L->print();

	L->deletesqlist(2);
	L->print();

	getchar();
	return 0;
}

原文链接:https://www.f2er.com/datastructure/383263.html

猜你在找的数据结构相关文章