【数据结构】 栈的模拟

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



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

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

相关文章

【啊哈!算法】算法3:最常用的排序——快速排序       ...
匿名组 这里可能用到几个不同的分组构造。通过括号内围绕的正...
选择排序:从数组的起始位置处开始,把第一个元素与数组中其...
public struct Pqitem { public int priority; ...
在编写正则表达式的时候,经常会向要向正则表达式添加数量型...
来自:http://blog.csdn.net/morewindows/article/details/6...