c_cpp 使用数组实现堆栈
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 使用数组实现堆栈相关的知识,希望对你有一定的参考价值。
#include<bits/stdc++.h>
#define MAX_SIZE 10 //defining max size of stack (since array)
using namespace std;
// #Stack #BasicProblem
bool isEmpty(int topIndex){
if(topIndex==-1){
return true;
}
return false;
}
bool Full(int topIndex){
if(topIndex==MAX_SIZE-1){
return true;
}
return false;
}
bool Push(int Stack[],int &topIndex,int push){
if(Full(topIndex)==true){
return false;
}else{
Stack[topIndex+1]=push;
topIndex++;
return true;
}
}
bool Pop(int &topIndex){
if(isEmpty(topIndex)==true){
return false;
}else{
topIndex--;
return true;
}
}
int main(){
cout<<"Instructions: \n";
cout<<"Type add to push onto stack"<<endl;
cout<<"Type del to pop from stack"<<endl;
cout<<"Type top to check the top element in stack"<<endl;
cout<<"Type exit to stop using the stack"<<endl;
int Stack[MAX_SIZE];
int topIndex=-1; //initializing an empty stack
while(1){
string instruction;
cout<<"Instruction: ";
cin>>instruction;
if(instruction=="exit"){
break;
}else if(instruction=="add"){
cout<<"Enter the element top be pushed"<<endl;
int push; //element to be pushed
cin>>push;
if(Push(Stack,topIndex,push)==true){
cout<<"Element successfully pushed"<<endl;
if(isEmpty(topIndex)==false){
cout<<"Top Element is:"<<Stack[topIndex]<<endl;
}
}else{
cout<<"ERROR: Stack is already full!"<<endl;
}
}else if(instruction=="del"){
if(Pop(topIndex)==true){
cout<<"Element was successfully popped"<<endl;
if(isEmpty(topIndex)==false){
cout<<"Top Element is:"<<Stack[topIndex]<<endl;
}else{
cout<<"Stack is now Empty!"<<endl;
}
}else{
cout<<"ERROR : Stack is empty!"<<endl;
}
}else if(instruction=="top"){
if(isEmpty(topIndex)==false){
cout<<"Top Element is:"<<Stack[topIndex]<<endl;
}else{
cout<<"ERROR : Stack is empty!"<<endl;
}
}else{
cout<<"ERROR : Unknown operation! Please try again"<<endl;
}
}
return 0;
}
以上是关于c_cpp 使用数组实现堆栈的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp 使用在堆栈上声明的数组(int myArray [3])和堆上的数组(int * myArray = new int [size]
c_cpp 使用Vector PopBack进行堆栈实现
c_cpp 使用类和链接列表实现堆栈
c_cpp 使用类和向量进行堆栈实现
c_cpp 按堆栈实现队列
c_cpp 将队列和堆栈实现添加到NSMutableArray类