算法导论——栈



补了点C++primer,会写一点简单的class了,然后马不停蹄用C++实现一下栈和队列。这一篇是栈,队列在下一篇。才学class难免不好看,但是用的多了就好了。我不仅写了导论上的3个函数,还写了一些别的,不过都是差不多的,简单。


头文件stack.h如下:

#pragma once
#ifndef _MY_STACK_H    
#define _MY_STACK_H
#define SIZE 100
#include<iostream>

class stack
{
public:
	using pos = char;
	typedef size_t poa;
	void initstack(stack &s);
	bool stackempty(stack& s) const;
	int gettop(stack &s, pos &i) const;
	int pushstack(stack &s, pos &i);
	int popstack(stack &s, pos &i);
	size_t stacklength(stack &s) const;
	void clearstack(stack &s);
private:
	pos mystack[SIZE];
	poa top;
};

void stack::initstack(stack &s)   //初始化一个栈
{
	this->top = 0; 
}

bool stack::stackempty(stack& s) const   //判断一个栈是否为空
{
	if (this->top <= 0)
		return 0;
	else
		return 1;
}

int stack::gettop(stack &s, pos &i) const    //取出栈顶元素
{
	if (this->top <= 0)
	{
		std::cout << "the stak is empty!!" << std::endl;
		return -1;
	}
	else
	{
		i = this->mystack[this->top - 1];
		return 0;
	}
}

int stack::pushstack(stack &s, pos &i)     //进栈
{
	if (this->top >= SIZE)
	{
		std::cout << "the stack is overflow!" << std::endl;
		return -1;
	}
	else
	{
		this->mystack[this->top++] = i;
		return 0;
	}
}

int stack::popstack(stack &s, pos &i)      //出栈
{
	if (this->top <= 0)
	{
		std::cout << "the stack is underflow!" << std::endl;
		return -1;
	}
	else
	{
		i = this->mystack[--this->top];
		return 0;
	}
}

size_t stack::stacklength(stack &s) const     //求栈的大小
{
	return this->top;
}

void stack::clearstack(stack &s)     //清空栈
{
	this->top = 0;
}
#endif


main函数如下:

#include<iostream>
#include"stack.h"
#include<stdlib.h>

using namespace std;

int main()
{
	stack my_stack;
	char s[] = { 'a','b','c','d','e' };
	char temp=0;
	char p1 = 'f', p2 = 'g';
	my_stack.initstack(my_stack);
	for (size_t i = 0; i < sizeof(s)/sizeof(s[0]); ++i)
		if (my_stack.pushstack(my_stack, s[i]) == -1)
		{
			cout << "the stack is overflow!" << endl;
		}
	cout << "出栈的元素:" << "  ";
	if(my_stack.popstack(my_stack,temp)==0)
		cout << temp<<"  ";
	if(my_stack.popstack(my_stack, temp)==0)
		cout << temp << endl;
	cout << "当前栈顶元素是:" << "  ";
	if (my_stack.gettop(my_stack, temp) == 0)
		cout << temp << endl;
	if (my_stack.pushstack(my_stack, p1) == -1)
		cout << "the stack is overflow!" << endl;
	if (my_stack.pushstack(my_stack, p2) == -1)
		cout << "the stack is overflow!" << endl;
	cout << "当前栈中元素个数是:" << "  " << my_stack.stacklength(my_stack) << endl;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值