在C++中堆栈实现
时间:2020-02-23 14:41:54 来源:igfitidea点击:
本文是关于C++中的数组堆栈实现。
堆栈是抽象数据类型
堆栈是一个有序数据结构,用于存储Lifo中的数据类型(首先换止)订单。
这意味着进入持续的元素首先退出(已处理)。
这就像一个同心环的塔保持在另一个。
当然,当我们开始一个接一个地将它们删除一个(例如:河内塔)时,将首先挑选最后一个。
堆栈是一种类似的数据结构(抽象数据类型,简短的ADT),其中插入和删除都在相同的结束时完成,即顶部。
堆栈只持有类似的数据类型。
插入过程命名为PUSH删除过程名为POP
堆栈上的操作
type_t =任何数据类型
基本操作:
PUSH(类型_t数据):它将数据类型type_t的数据插入到堆栈
type_t pop():从堆栈中删除最顶部元素并返回它
其他操作:
type_t top():返回最顶层元素
bool isempty():如果堆栈为空,则返回true,否则返回false
bool arfull():返回true如果stack已满,则返回false
int size():返回堆栈的大小
使用C++中的数组堆栈实现
准备工作:1.
Top变量2.数组即堆栈array,以便使用阵列实现堆栈我们需要做的是实现这些操作。
以下是详细的代码。
#include <bits/stdc++.h>
using namespace std;
#define MAX_SIZE 1024
//declare our pre-reuisites
int stack_array[MAX_SIZE]; //globally declared array to act like stack
int top=-1; //top variavle initialized to -1 for empty stack
//implement stack operations
//1. implement isEmpty()
bool isEmpty(){
if(top==-1) //empty stack
return true;
else
return false;
}
//2. Implement isFull()
bool isFull(){
if(top==MAX_SIZE-1)
return true;
else
return false;
}
//3. Implement push operation
void push(int data){
if(isFull()){
cout<<"Stack is full\n";
return;
}
else{
stack_array[++top]=data;//first top is increased by 1 and then stack[top]=data
cout<<data<<" is pushed\n";
}
}
//4. Implement Pop operation
int pop(){
if(isEmpty()){
cout<<"Stack is empty\n";
return INT_MIN;
}
else{
return stack_array[top--]; //top is decreased after popping
}
}
//5. implement size function
int size(){
return top+1;
}
//6. implement top
int top_stack(){
if(isEmpty()){
cout<<"stack is empty\n";
return INT_MIN;
}
else
return stack_array[top];
}
//main function
int main(){
//menu for operations
//press 1 for push (with data)
//press 2 for pop()
//press 3 for top()
//press 4 for size()
//press 0 to exit()
cout<<"press 1 for push\n";
cout<<"press 2 for pop()\n";
cout<<"press 3 for top()\n";
cout<<"press 4 for size()\n";
cout<<"press 0 for exit\n";
int choice;
cout<<"press your choice\n";
cin>>choice;
while(choice){
if(choice==1){
int data;
cout<<"Enter element\n";
cin>>data;
push(data);
}
else if(choice==2){
int item=pop();
if(item==INT_MIN){}
else
cout<<"Popped element: "<<item<<endl;
}
else if(choice==3){
int item=top_stack();
if(item==INT_MIN){}
else
cout<<"Top element: "<<item<<endl;
}
else if(choice==4){
cout<<"Size is: "<<size()<<endl;
}
else
cout<<"Invalid number, try again!\n";
cout<<"press your choice\n";
cin>>choice;
}
cout<<"Exiting...\n";
return 0;
}

