【数据结构】顺序表

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


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

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值