Assignment-9 (Stack LL)
Assignment-9 (Stack LL)
—------------------------------------------------------------------------------------------------------------------------------
Assignment-9
Program to implement stack using linked list
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int val)
{
data = val;
next = NULL;
}
};
class Stack {
private:
Node* top;
public:
Stack() {
top = nullptr;
}
void pop() {
if (isEmpty()) {
cout << "Stack Underflow\n";
return;
}
Node* temp = top;
top = top->next;
delete temp;
}
int peek() {
if (isEmpty()) {
cout << "Stack is empty\n";
return -1;
}
return top->data;
}
bool isEmpty() {
return top == nullptr;
}
};
int main() {
int size;
int ch,ele;
cout<<"Devesh Srivastava";
cout<<"\nRollNo: 2200270140013\n\n";
cout<<"Enter the size of stack: ";
cin>>size;
Stack stack;
// stack.push(1);
// stack.push(2);
// stack.push(3);
// cout << stack.peek() << endl; // Output: 3
// stack.pop();
// cout << stack.peek() << endl; // Output: 2
// stack.pop();
// cout << stack.peek() << endl; // Output: 1
// stack.pop();
// cout << stack.isEmpty() << endl; // Output: 1 (true)
// return 0;
// }
do
{
cout<<"----------------------------------------------------------------";
cout<<"\n\tStack menu is given, Press the options given below...";
cout<<"\n\t\t1. Push ";
cout<<"\n\t\t2. Pop";
cout<<"\n\t\t3. Peek";
cout<<"\n\t\t4. Isempty";
cout<<"\n\t\t5. Exit";
cout<<"\n---------------------------------------------------------------";
cout<<"\n\nEnter you choice: ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\nEnter the element to insert: ";
cin>>ele;
stack.push(ele);
cout<<"\n\n";
break;
case 2:
stack.pop();
cout<<"\n\n";
break;
case 3:
cout<<"\nPeek of the stack: \n";
cout<<stack.peek();
cout<<"\n\n";
break;
case 4:
cout<<"\n Check it is empty or not: \n";
if(stack.isEmpty())
cout<<"\nStack is empty";
else
cout<<"\nStack is not empty";
cout<<"\n\n";
break;
case 5:
cout<<"\n..................Exit.......................";
break;
default:
cout<<"\nWrong Input....try again";
break;
}
} while (ch!=5);
return 0;
}
OUTPUT