【数据结构】 栈的模拟

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

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



/***
数据结构:栈的模拟
***/

#ifndef __STACK_H__
#define __STACK_H__

#define MAXSIZE 100

typedef char ElemType;
typedef struct{
	ElemType *top;
	ElemType *base;
	int stackSize;
} sqStack;

class Stack{
public:
	Stack();
	~Stack();

	void initStack();
	void push(ElemType e);
	ElemType pop();
	int stackLongth();
	void clearStack();
	void destoryStack();
	void print();

private:
	sqStack *items;

};

#endif // __STACK_H__



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

Stack::Stack()
{
	this->initStack();
}
Stack::~Stack()
{
	this->destoryStack();
}

void Stack::initStack()
{
	this->items = new sqStack();
	this->items->base = (ElemType *) new ElemType[MAXSIZE];
	if (!this->items->base)
	{
		exit(0);
	}
	this->items->top = this->items->base;
	this->items->stackSize = MAXSIZE;
}
void Stack::push(ElemType e)
{
	*(this->items->top) = e;
	++(this->items->top);
}
ElemType Stack::pop()
{
	if (this->items->base == this->items->top)
	{
		cout<<"the stack is NULL"<<endl;
		exit(0);
	}

	--(this->items->top);
	return *(this->items->top);
}
int Stack::stackLongth()
{
	return (this->items->top - this->items->base);
}
void Stack::clearStack()
{
	this->items->top = this->items->base;
}
void Stack::destoryStack()
{
	for (int i=0;i!=this->stackLongth();++i)
	{
		delete this->items->base;
		++(this->items->base);
	}

	this->items->base = NULL;
	this->items->top = NULL;
	this->items->stackSize = 0;
}
void Stack::print()
{
	cout<<"show items:"<<endl;
	for (ElemType *e=this->items->base;e!=this->items->top;++e)
	{
		cout<<*e<<endl;
	}
}

int main()
{
	Stack *stack = new Stack();

	char ch[11] = "1011011001";
	for (int i=0;i!=10;++i)
	{
		stack->push(ch[i]);
	}
	stack->print();
	stack->push('1');
	stack->print();
	cout<<"temp char is:"<<stack->pop()<<endl;
	stack->print();
	cout<<"stack longth:"<<stack->stackLongth()<<endl;
	char c;
	int sum = 0;
	int lon = stack->stackLongth(); 
	for (int i=0;i<lon;++i)
	{
		c = stack->pop();
		cout<<"item:"<<c<<endl;
		sum += (c - 48)*pow(2.0,i);
	}
	cout<<"decimail :"<<sum<<endl;

	getchar();
	return 0;
}

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