Implement a Stack to store a character in the node. Implement the following operations
push, pop and peek:.
void push (char c);
char pop();
char peek();
int isEmpty();
void printStack();
SOLUTION TO THE ABOVE QUESTION
SOLUTION CODE
// C++ program to Implement a stack
//using singly linked list
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// Declare linked list node
struct Node
{
char data;
struct Node* link;
};
struct Node* top;
//function push to add a character
// data in the stack insert at the beginning
void push(char data)
{
// Create new node temp and allocate memory
struct Node* temp;
temp = new Node();
// Check if stack (heap) is full.
// Then inserting an element would
// lead to stack overflow
if (!temp)
{
cout << "\nHeap Overflow";
exit(1);
}
// Initialize data into temp data field
temp->data = data;
// Put top pointer reference into temp link
temp->link = top;
// Make temp as top of Stack
top = temp;
}
// function isEmpty to check if the stack is empty or not
int isEmpty()
{
return top == NULL;
}
// function to return top element in a stack
char peek()
{
struct Node* temp;
// Check for stack underflow
if (top == NULL)
{
cout << "\nStack Underflow";
exit(1);
}
else
{
temp = top;
return temp->data;
}
}
// function to pop top element from the stack
void pop()
{
struct Node* temp;
  Â
// Check for stack underflow
if (top == NULL)
{
cout << "\nStack Underflow" << endl;
exit(1);
}
else
{
// Top assign into temp
temp = top;
// Assign second node to top
top = top->link;
// Destroy connection between
// first and second
temp->link = NULL;
// Release memory of top node
free(temp);
}
}
// Function to print all the
// elements of the stack
void printStack()
{
struct Node* temp;
// Check for stack underflow
if (top == NULL)
{
cout << "\nStack Underflow";
exit(1);
}
else
{
temp = top;
while (temp != NULL)
{
// Print node data
cout << temp->data << ", ";
// Assign temp link to temp
temp = temp->link;
}
}
}
// Driver Code
int main()
{
// Push the elements of stack
push('a');
push('b');
push('c');
push('d');
push('e');
push('f');
// Display stack elements
cout<<"\nThe following are the elements of our stack: "<<endl;
printStack();
// Print top element of stack
cout << "\n\nTop element in our stack is "
<< peek() << endl;
// Delete top elements of stack
pop();
pop();
// Display stack elements
cout<<"\nNow the elemnts in our stack after poping are: "<<endl;
printStack();
// Print top element of stack
cout << "\n\nTop element after popping is: "
<< peek() << endl;
return 0;
}
SAMPLE PROGRAM OUTPUT
Comments
Leave a comment