0% found this document useful (0 votes)
8 views5 pages

Assignment-9 (Stack LL)

Stack linked list assignment

Uploaded by

srivastavad1212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views5 pages

Assignment-9 (Stack LL)

Stack linked list assignment

Uploaded by

srivastavad1212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Name- Devesh Srivastava Session: 2022-2023

Roll No- 2200270140013 Assignment- 9


Group- G1

—------------------------------------------------------------------------------------------------------------------------------

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 push(int val) {


Node* newNode = new Node(val);
newNode->data = val;
newNode->next = top;
top = newNode;
}

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

You might also like