栈结构与应用
1 顺序栈
#ifndef __STACK__
#define __STACK__
#include <iostream>
using namespace std;
#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;
}