栈结构与应用

栈结构与应用

1 顺序栈

#ifndef __STACK__
#define  __STACK__

#include <iostream>
using namespace std;

//#define ElemType char 
#define ElemType char 
#define STACK_INIT_SIZE 8
#define STACK_INC_SIZE   3

class Stack
{
public:
	bool Inc();
	void InitStack();
	bool IsFull();
	bool IsEmpty();
	void Push(ElemType x);
	void Pop();
	bool GetTop(ElemType *v);
	void Show();
	int Length();
	void Clear();
	~Stack();
private:
	ElemType* base;
	int top;
	int capacity;
};
#endif
#include "Stack.h"

bool Stack::Inc()
{
	ElemType* newBase = (ElemType*)realloc(base, sizeof(ElemType) * (STACK_INC_SIZE + STACK_INIT_SIZE));
	if (newBase == NULL)
	{
		cout << "内存不足,无法申请空间" << endl;
		return false;
	}
	base = newBase;
	capacity = STACK_INC_SIZE + STACK_INIT_SIZE;
	return true;
}

void Stack::InitStack()
{
	base = (ElemType*)malloc(sizeof(ElemType) * STACK_INIT_SIZE);
	capacity = STACK_INIT_SIZE;
	top = 0;
}

bool Stack::IsFull()
{
	return top >= capacity;
}

bool Stack::IsEmpty()
{
	return top == 0;
}

void Stack::Push(ElemType x)
{
	if (IsEmpty() && !Inc())
	{
		return;
	}
	base[top++] = x;
}

void Stack::Pop()
{
	if (IsEmpty())
	{
		cout << "栈已空,无法出栈" << endl;
		return;
	}
	top--;
}

bool Stack::GetTop(ElemType *v)
{
	if (IsEmpty())
	{
		cout << "栈已空,无法出栈,无法获取栈顶元素" << endl;
		return false;
	}
	*v = base[top - 1];
	return true;
}

void Stack::Show()
{
	for (int i = top - 1; i >= 0; i--)
	{
		cout << base[i] << endl;
	}
}

int Stack::Length()
{
	return top;
}

void Stack::Clear()
{
	top = 0;
}

Stack::~Stack()
{
	if (base != NULL)
	{
		delete base;
		base = NULL;
	}
	capacity = 0;
	top = 0;
}


2 应用

#define _CRT_SECURE_NO_WARNINGS
#include "Stack.h"


void ConvertToEight(int value)
{
	Stack s;
	s.InitStack();
	while (value)
	{
		s.Push(value % 8);
		value = value / 8;
	}
	s.Show();
}


bool Check(const char* str)
{
	Stack s;
	s.InitStack();
	char val;
	while (*str != '\0')
	{
		if (*str == '[' || *str == '(')
		{
			s.Push(*str);
		}
		else if (*str == ']')
		{
			s.GetTop(&val);
			if (val == '[')
			{
				s.Pop();
			}
			else
			{
				return false;
			}
		}
		else if (*str == ')')
		{
			s.GetTop(&val);
			if (val == '(')
			{
				s.Pop();
			}
			else
			{
				return false;
			}
		}
		str++;
	}
	if (s.IsEmpty())
	{
		return true;
	}
	else
	{
		return false;
	}
}

int main()
{
	// 十进制转八进制
	int value = 47183;
	ConvertToEight(value);

	// 模式匹配
	const char *str = "[([()]))]";
	bool flag = Check(str);
	if (flag)
	{
		cout << "OK" << endl;
	}
	else
	{
		cout << "ERROR" << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值