相信大家对栈都不陌生,栈作为一种基础的数据结构,在很多地方都会用到,在这里整理一下顺序栈和链式栈的一些基础操作。
1.顺序栈
#pragma onc
# define MAX_SIZE 10
class SeqStack
{
public:
SeqStack():top(-1),size(MAX_SIZE)
{
arr = new int[size];
}
~SeqStack()
{
delete[] arr;
}
//判断栈满
bool Full()
{
return top == size - 1;
}
//判断栈空
bool Empty()
{
return top == -1;
}
//入栈
void Push(int value)
{
if (!Full())
{
arr[++top] = value;
}
}
//出战
int Pop()
{
if (!Empty())
{
return arr[top--];
}
}
//得到栈顶元素
int GetTopEle()
{
if (!Empty())
{
return arr[top];
}
}
private:
int top;
int size;
int* arr;
};
2.链式栈
#pragma once
# define VALUE_TYPE int
typedef struct Node
{
VALUE_TYPE data;
Node* next;
};
class LinkStack
{
public:
LinkStack():top(nullptr),length(0)
{
}
~LinkStack()
{
if (top != nullptr)
{
while (!Empty())
{
}
}
}
//判断栈是否为空
bool Empty()
{
return length == 0;
}
//入栈操作
bool Push(VALUE_TYPE value)
{
Node* newNode = new Node;
newNode->data = value;
if (!Empty())
{
newNode->next = top;
top = newNode;
}
else
{
top = newNode;
top->next = nullptr;
}
++length;
return true;
}
//出栈操作
VALUE_TYPE Pop()
{
if (!Empty())
{
Node *node = top;
top = top->next;
int data = node->data;
delete node;
--length;
return data;
}
}
//获取栈顶元素
VALUE_TYPE GetTopEle()
{
if (!Empty())
{
return top->data;
}
}
private:
Node* top;
int length;
};