加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

【数据结构】顺序表

发布时间:2020-12-15 06:33:29 所属栏目:安全 来源:网络整理
导读:学习数据结构基础,如有错误,请指正 /***数据结构:顺序表的模拟***/#ifndef __SQLIST_H__ #define __SQLIST_H__typedef int ElemType;#define MAXSIZE 100#define ADDSIZE 100class SqList{private:ElemType *elem;int longth;int size;public:SqList();~S

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


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

#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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读