前两天自己照着一些博客仿写了栈的C++,其间也出了一些问题,但是通过调试,各个基本函数都得到了验证。当然可能存在我不知道的问题,如果有小伙伴验证我代码的时候出现了问题希望可以告知我一下,非常感谢。
代码如下:
Stack.h文件
#pragma once
//栈的基本函数实现
#include<iostream>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int ElemType;
//定义栈节点
struct StackNode
{
ElemType value;
StackNode *ptr;
};
//栈类及其相关函数
class Stack
{
public:
//构造函数
Stack();
//析构函数
~Stack();
//初始化栈
bool InitStack();
//销毁栈
bool DestroyStack();
//清空栈
void ClearStack();
//判断栈是否为空。是返回true,否则返回false
bool StackEmpty();
//返回栈长度
int StackLength();
//获取栈顶元素
ElemType GetTop();
//压栈
void Push(ElemType e);
//出栈
ElemType Pop();
//遍历栈内元素并输出显示,但同时会清空栈
void StackTraverse();
private:
StackNode *top;
StackNode *base;
int stacksize;
};
Stack.cpp文件
#include"Stack.h"
#include<stdio.h>
#include<stdlib.h>
//构造函数
Stack::Stack()
{
top = NULL;
base = NULL;
stacksize = 0;
}
//析构函数
Stack::~Stack()
{
}
//栈初始化
bool Stack::InitStack()
{
base = new StackNode[STACK_INIT_SIZE];
if (!base)
{
std::cout << "内存分配失败" << std::endl;
return false;
}
top = base;
stacksize = STACK_INIT_SIZE;
return true;
}
//销毁栈
bool Stack::DestroyStack()
{
if (base)
{
delete base;
base = NULL;
top = NULL;
stacksize = 0;
std::cout << "栈销毁成功" << std::endl;
return true;
}
else
{
std::cout << "栈内存分配失败,不能销毁栈" << std::endl;
return false;
}
}
//清空栈
void Stack::ClearStack()
{
top = base;
}
//判断栈是否为空
bool Stack::StackEmpty()
{
if (base == top)
{
return true;
}
else
{
return false;
}
}
//返回栈元素长度
int Stack::StackLength()
{
return (top - base);
}
//获取栈顶元素
ElemType Stack::GetTop()
{
ElemType e;
if (top >base)
{
e =(top--)->value;
return e;
}
else
{
return false;
}
}
//压栈
void Stack::Push(ElemType e)
{ //若栈满,追加存储空间
if (top -base >= stacksize)
{
base = (StackNode*)realloc(base,stacksize + STACKINCREMENT*sizeof(StackNode));
if (!base)
{
std::cout << "栈内存分配失败" << std::endl;
exit(-1);
}
top = base +stacksize;
stacksize += STACKINCREMENT;
}
/*注意入栈时一定先赋值,然后栈顶再加1*/
top->value = e;
top++;
stacksize++;
}
/*这种压栈方式存在问题,后续思考一下*/
//void Stack::Push(ElemType data)
//{
// StackNode *temp;
// temp = (StackNode *)new StackNode[1];
// temp->value = data;
// temp->next = NULL;
// if (stacksize == 0)
// { top = (StackNode *)new StackNode[1];
// base = temp;
// }
// top->next = temp;
// top = temp;
// stacksize++;
// std::cout << "Push: 入栈成功!" << std::endl;
//}
//出栈
ElemType Stack::Pop()
{
ElemType e;
if (top == base)
{
std::cout << "栈为空,无法出栈" << std::endl;
exit(-1);
}
else
{
e = (--top)->value;
top->value = 0;
stacksize--;
return e;
}
}
//遍历栈内容
void Stack::StackTraverse()
{
ElemType e=0;
if (top==base)
{
std::cout << "栈为空,无法出栈" << std::endl;
exit(-1);
}
else
{
std::cout << "栈内元素为:";
do
{
e=Pop();
std::cout <<e<< " ";
//std::cout << (--top)->value << " ";
} while (top!=base);
std::cout << std::endl;
}
}