A stack using an array is an abstract data structure that contains a collection of similar data elements. Stack working on the LIFO. That means the last element that is pushed will be the first element that is going to be popped. Some of the stack operations using an array in the stack are listed and implemented below.
- isEmpty: This function determines whether or not the stack is empty.
- Push: This adds the element to the top of the stack.
- Pop: This removes the data from the top of the stack.
- Peek: This returns the top element of the stack.
- Display: This function displays all elements of the stack.
#include <iostream>
using namespace std;
#define N 5
//Array declaration by specifying size and Top of stack
int stack[N], top = -1;
//Function to check the stack if it Empty return true and false
bool isEmpty()
{
if (top == -1)
{
return true;
}
return false;
}
//Function to push the number into the stack
void push(int number)
{
if (top == N)
{
cout << "Stack is Overflow \n";
}
else
{
stack[top + 1] = number;
top++;
}
}
//Function to display the elements of the stack
void display()
{
if (isEmpty())
{
cout << "Stack is Empty\n";
}
else
{
cout << "List of all Elements: ";
for (int i = top; i >= 0; i--)
{
cout << stack[i];
cout << "\n";
}
}
}
//Function to pop the element from the stack
void pop()
{
if (isEmpty())
{
cout << "Stack is Empty\n";
}
else
{
cout << "Element Pop: ";
cout << stack[top];
cout << "\n";
top--;
}
}
//Function to take a look at top of a stack
void peek()
{
if (isEmpty())
{
cout << "Stack is Empty\n";
}
else
{
cout << stack[top];
cout << "\n";
}
}
//Main function
int main()
{
while (1)
{
cout << "Enter Your Choice of Operation from the following: \n";
cout << "1: Push.\n";
cout << "2: Pop.\n";
cout << "3: Peek.\n";
cout << "4: Display.\n";
cout << "5: Is Empty.\n";
cout << "6: To Exit. \n";
int x;
cin >> x;
if (x == 6)
{
break;
}
switch (x)
{
case 1:
int number;
cout << "Enter a Number to push: ";
cin >> number;
push(number);
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
display();
break;
case 5:
cout << isEmpty();
break;
}
}
return 0;
}
A Windows 10 certification can help you prove your skills in the Microsoft Windows 10 operating system and it can improve your chances of getting hired. StudySection offers a Windows 10 Certification Exam for beginner level as well as professional level individuals in the Microsoft Windows 10 operating system.