Hot Topics
Data Structure
A linked list is data structure that has two parts, one in which the data is stored and another in which that address of next data is stored.So here we are going to perform the operations of stack using linked list. The head of the linked list is considered to be the top of the stack.Whenever we enter a linked list the head/top gets updated and after the final input in stack the head/top holds the address of last inserted node in the stack.
Operations in stack
push():To push element into stack we have to push a new element at the beginning of the linked list everytime.
pop():Take out the first element of the linked list.
peak():The top element of stack or the first element of the linked list.
empty():The stack can be said as empty when the top is not pointing to an index which is a part of stack.
Codes are given bellow
// using singly linked list
#include
using namespace std;
// Declare linked list node
struct Node
{
int data;
Node *link;
};
Node *top;
// Utility function to add an element
// data in the stack insert at the beginning
void push(int data)
{
// Create new node temp and allocate memory in heap
Node *temp = new Node();
// Check if stack (heap) is full.
// Then inserting an element would
// lead to stack overflow
if (!temp)
{
cout <data = data;
// Put top pointer reference into temp link
temp->link = top;
// Make temp as top of Stack
top = temp;
}
// Utility function to check if
// the stack is empty or not
int isEmpty()
{
// If top is NULL it means that
// there are no elements are in stack
return top == NULL;
}
// Utility function to return top element in a stack
int peek()
{
// If stack is not empty , return the top element
if (!isEmpty())
return top->data;
else
exit(1);
}
// Utility function to pop top
// element from the stack
void pop()
{
Node *temp;
// Check for stack underflow
if (top == NULL)
{
cout << "\nStack Underflow" <link;
// This will automatically destroy
// the link between first node and second node
// Release memory of top node
// i.e delete the node
free(temp);
}
}
// Function to print all the
// elements of the stack
void display()
{
Node *temp;
// Check for stack underflow
if (top == NULL)
{
cout << "\nStack Underflow";
exit(1);
}
else
{
temp = top;
while (temp != NULL)
{
// Print node data
cout <data <link;
}
}
}
int main()
{
// Push the elements of stack
push(11);
push(22);
push(33);
push(44);
// Display stack elements
display();
// Print top element of stack
cout << "\nTop element is " << peek() << endl;
// Delete top elements of stack
pop();
pop();
// Display stack elements
display();
// Print top element of stack
cout << "\nTop element is " << peek() << endl;
return 0;
}
Output:
44 33 22 11
Top element is 44
22 11
Top element is 22