这期内容当中小编将会给大家带来有关Java数据结构中栈的用法,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
栈是先进后出的特殊线性表,只允许在表的末端进行插入和删除,后面将介绍两种实现栈的方式,分别是基于数组的实现、基于链表的实现。
class Mystack
{
public:
Mystack() {}
virtual void push(int &x) = 0;
virtual bool pop(int &x) = 0;
virtual bool Top(int &x) const = 0;
virtual bool IsEmpty()const = 0;
virtual bool IsFull()const = 0;
virtual int getSize()const = 0;
};
定义:
#pragma once
#include "Mystack.h"
#include <iostream>
#include <assert.h>
using namespace std;
const int stackIncreament = 20;
class SeqStack : public Mystack
{
public:
SeqStack(int sz = 50); //建立一个空栈
~SeqStack() { delete[]elements; } //析构函数
//如果栈满,则溢出程序处理,否则插入x
void push(int &x);
//如果栈空,则返回FALSE,否则使用x传递栈顶的值,top-1
bool pop(int &x);
//如果栈空,则返回FALSE,否则使用x传递栈顶的值
bool Top(int &x);
//判断栈是否为空
bool IsEmpty()const {
return (top == -1) ? true : false;
}
//判断栈是都为满
bool IsFull()const {
return (top == maxSize - 1) ? true : false;
}
//获取栈当前的size
int getSize()const {
return top + 1;
}
//将栈置空
void MakeEmpty() {
top = -1;
}
//重载 操作 <<
friend ostream& operator<<(ostream& os, SeqStack& s);
private:
int *elements; //栈数组指针
int top; //栈顶指针
int maxSize; //栈的最大容量
void overflowProcess(); //溢出处理程序
};
实现:
#include "SeqStack.h"
SeqStack::SeqStack(int sz):top(-1),maxSize(sz)
{
elements = new int[maxSize]; //创建栈的数组空间
assert(elements == NULL); //断言:动态分配是否成功
}
void SeqStack::push(int & x)
{
//首先判断栈是否已满,满则转入溢出处理
if(IsFull() == true){
overflowProcess();
}
elements[++top] = x; //将top+1,再插入值x
}
bool SeqStack::pop(int & x)
{
//先判断是否为空,为空则返回FALSE
if (IsEmpty() == true) {
return false;
}
x = elements[top--]; //使用x返回top所指,再讲top-1
return true;
}
bool SeqStack::Top(int & x)
{
//空栈则为FALSE
if (IsEmpty() == true) {
return false;
}
//栈不为空,则返回栈顶元素的值
x = elements[top];
return true;
}
ostream& operator<<(ostream& os, SeqStack& s) {
//输出栈中元素
os << "top = " << s.top << endl;
for (int i = 0; i <= s.top; ++i) {
os << i << ": " << s.elements[i] << endl;
}
return os;
}
void SeqStack::overflowProcess()
{
//栈溢出时,扩充栈的存储空间
int *Newelement = new int[maxSize + stackIncreament];
if (Newelement == NULL) {
cout << "分配内存失败";
exit(1);
}
for (int i = 0; i <= top; ++i) {
Newelement[i] = elements[i];
}
delete[] elements;
elements = Newelement;
}
上述就是小编为大家分享的Java数据结构中栈的用法了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。