The stack is a data structure. To implement a stack data structure, we can use both linked list or array. Below are examples of both types of implementation.

## Using Linked List

class Node(): def __init__(self, data): self.data = data self.next = None class Stack(): def __init__(self): self.head = None def push(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def pop(self): if self.head == None: return 'Stack is empty' self.head = self.head.next def peek(self): if self.head == None: return 'Stack is empty' return self.head.data def is_empty(self): return self.head == None stack = Stack() print(stack.is_empty()) stack.push(1) stack.push(3) stack.push(5) stack.push(7) stack.push(9) print(stack.peek()) stack.pop() print(stack.peek()) print(stack.is_empty())

## Using Python List

lst = [] # push lst.append(1) lst.append(2) lst.append(3) lst.append(4) print(lst) # [1, 2, 3, 4] # pop lst.pop() print(lst) # [1, 2, 3] # is_empty print(len(lst) == 0) # False

Comments are closed.