When it is required to implement a stack data structure using a linked list, a method to add (push values) elements to the linked list, and a method to delete (pop values) the elements of the linked list are defined.
Below is a demonstration for the same −
class Node: def __init__(self, data): self.data = data self.next = None class Stack_structure: def __init__(self): self.head = None def push_val(self, data): if self.head is None: self.head = Node(data) else: newNode = Node(data) newNode.next = self.head self.head = newNode def pop_val(self): if self.head is None: return None else: del_Val = self.head.data self.head = self.head.next return del_Val my_instance = Stack_structure() while True: print('push <value>') print('pop') print('quit') my_input = input('What action would you like to perform ? ').split() operation = my_input.strip().lower() if operation == 'push': my_instance.push_val(int(my_input)) elif operation == 'pop': del_Val = my_instance.pop_val() if del_Val is None: print('The stack is empty.') else: print('The deleted value is : ', int(del_Val)) elif operation == 'quit': break
push <value> pop quit What action would you like to perform ? push 56 push <value> pop quit What action would you like to perform ? push 78 push <value> pop quit What action would you like to perform ? push 90 push <value> pop quit What action would you like to perform ? pop The deleted value is : 90 push <value> pop quit What action would you like to perform ? quit
The ‘Node’ class is created.
Another ‘Stack_structure’ class with required attributes is created.
It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’.
A method named ‘push_val’ is defined, that helps add a value to the stack.
Another method named ‘pop_val’ is defined, that helps delete a value from the top of the stack, and returns the deleted value.
An instance of the ‘Stack_structure’ is created.
Three options are given, such as ‘push’, ‘pop’, and ‘quit’.
The ‘push’ option adds a specific value to the stack.
The ‘pop’ option deletes the topmost element from the stack.
The ‘quit’ option comes out of the loop.
Based on the input/choice by user, the respective operations are performed.
This output is displayed on the console.