Stack
Stack
1. A Node class, which serves as the building block for the linked
list. The Node class should have an __init__ method that
initializes the following attributes:
● value: The value of the node.
● next: A reference to the next node in the list, initialized to
None.
2. The Stack class should have an __init__ method that
initializes the stack with a single node, using the given value. The
__init__ method should perform the following tasks:
● Create a new instance of the Node class using the provided
value.
● Set the top attribute of the Stack class to point to the new
node.
● Initialize a height attribute for the Stack class, which
represents the current number of nodes in the stack, and
set it to 1.
Step 1: Define the Node class
python
Copy code
class Node:
The Stack class will use the Node class to represent each element in
the stack.
python
Copy code
class Stack:
1. Node Initialization:
○ When creating a node, we store a value and set the next
pointer to None because it does not yet point to any other
node.
2. Stack Initialization:
○ The Stack class initializes the stack with one element.
○ A Node is created and assigned to self.top, representing
the topmost element in the stack.
○ The height attribute tracks the number of nodes in the
stack, which starts at 1 since the stack is initialized with
one node.
class Node:
def __init__(self,value):
self.value=value
self.next=None
class Stack:
def __init__(self,value):
new_node=Node(value)
self.top=new_node
self.height= 1
my_stack = Stack(4)
print('Top:', my_stack.top.value)
print('Height:', my_stack.height)
EXPECTED OUTPUT:
----------------
Top: 4
Height: 1
Stack:Push
Implement the push method for the Stack class that adds
a new node with a given value to the top of the stack.
● Stack: A linear data structure that follows the Last In, First Out (LIFO) principle.
● Top of Stack: Refers to the most recently added element, which is the first one to be
removed.
● Operations:
○ Push: Adds an element to the top of the stack.
○ Pop: Removes the element from the top of the stack.
○ Peek (Optional): Returns the top element without removing it.
○ isEmpty (Optional): Checks if the stack is empty.
Python lists allow us to efficiently add and remove elements from the end using:
● append() to add an element to the end of the list (top of the stack).
● pop() to remove and return the last element from the list (top of the stack).
python
Copy code
class Stack:
def __init__(self):
self.stack = [] # Step 1: Initialize an empty list to
represent the stack
python
Copy code
def __init__(self):
self.stack = [] # Initialize an empty list for the stack
Implementing the push Method
The push method adds a new element to the top of the stack.
python
Copy code
def push(self, value):
self.stack.append(value) # Step 2: Append the value to the end
of the list
1. Use append() to add value to the end of the list, which is the top of the stack.
The pop method removes and returns the top element of the stack.
python
Copy code
def pop(self):
if len(self.stack) == 0: # Step 1: Check if stack is empty
return None # If empty, return None
return self.stack.pop() # Step 2: Use pop() to remove and
return the last element
1. Check if the stack is empty by checking the length of the list (len(self.stack) ==
0).
2. If empty, return None.
3. If not empty, use pop() to remove and return the last element from the list.
The peek method returns the top element of the stack without removing it.
python
Copy code
def peek(self):
if len(self.stack) == 0: # Step 1: Check if stack is empty
return None # If empty, return None
return self.stack[-1] # Step 2: Return the last element
in the list
python
Copy code
def isEmpty(self):
return len(self.stack) == 0 # Return True if stack length is
0, else False
python
Copy code
class Stack:
def __init__(self):
self.stack = [] # Initialize an empty list for
the stack
def pop(self):
if len(self.stack) == 0: # Check if stack is empty
return None # If empty, return None
return self.stack.pop() # Remove and return the top
element
def peek(self):
if len(self.stack) == 0: # Check if stack is empty
return None # If empty, return None
return self.stack[-1] # Return the top element without
removing it
def isEmpty(self):
return len(self.stack) == 0 # Return True if stack is empty,
else False
Example Usage
python
Copy code
my_stack = Stack() # Initialize an empty stack
Explanation of Example
1. Push Operations: Elements 4, 7, and 9 are added to the stack. The stack list will now
look like [4, 7, 9].
2. Pop Operation: Calling pop() removes the top element, 9, leaving [4, 7] and returns
9.
3. Peek Operation: peek() returns the current top element (7) without removing it.
4. isEmpty Operation: isEmpty() checks if the stack is empty. It returns False since
[4, 7] still has elements.
● Simple Syntax: Python’s built-in list methods append and pop make stack operations
straightforward.
● Dynamic Size: Unlike arrays in some other languages, lists in Python can dynamically
grow or shrink as elements are added or removed.
Limitations
● Performance: In Python, lists are generally efficient, but in cases where performance is
critical, a deque from the collections module may offer faster pop and append
operations on larger datasets.