Adding A Node To The Stack (Push Operation)
Adding A Node To The Stack (Push Operation)
In linked list implementation of stack, the nodes are maintained non-contiguously in the
memory. Each node contains a pointer to its immediate successor node in the stack. Stack is
said to be overflown if the space left in the memory heap is not enough to create a node.
The top most node in the stack always contains null in its address field. Lets discuss the way
in which, each operation is performed in linked list implementation of stack.
Check for the underflow condition: The underflow condition occurs when we try to
pop from an already empty stack. The stack will be empty if the head pointer of the list
points to null.
Adjust the head pointer accordingly: In stack, the elements are popped only from one
end, therefore, the value stored in the head pointer must be deleted and the node
must be freed. The next node of the head node now becomes the head node
Time Complexity : o(n)
Display the nodes (Traversing)
Displaying all the nodes of a stack needs traversing all the nodes of the
linked list organized in the form of stack. For this purpose, we need to
follow the following steps.Copy the head pointer into a temporary
pointer.Move the temporary pointer through all the nodes of the list and
print the value field attached to every node.
isEmpty() Function
The isEmpty function checks whether the stack is empty or not. To
implement this function with a singly linked list, we just check if the head is
NULL or not. If the head is NULL, it means that the list is empty, so we will
return true. If the head is not NULL, it means that the list is not empty, so
we will return false.
Program:
OUTPUT: -
Conclusion:-
Stack is a linear data structure that follows the Last in, First Out Principle
(LIFO).
Stack can be represented using nodes of a linked list.
Stack supports operations such as push, pop, size, peek, and is Empty.
Elements can be pushed or popped from one end only.
Push and Pop operations take O(1) time.