0% found this document useful (0 votes)
3 views

Stack

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Stack

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Stack: Constructor

Create a Stack class that represents a last-in, first-out (LIFO) data


structure using a linked list implementation.

The Stack class should contain the following components:

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

This class represents an individual node in the linked list.

python

Copy code

class Node:

def __init__(self, value):

self.value = value # Initialize the


node's value

self.next = None # Initialize the next


pointer to None

Step 2: Define the Stack class

The Stack class will use the Node class to represent each element in
the stack.

python

Copy code

class Stack:

def __init__(self, value):


new_node = Node(value) # Create a new
node with the given value

self.top = new_node # Set the top of


the stack to the new node

self.height = 1 # Initialize the


height of the stack to 1

Explanation of Each Part

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.

The method should perform the following tasks:

1. Create a new instance of the Node class using the


provided value.
2. Set the next attribute of the new node to point to the
current top node.
3. Update the top attribute of the Stack class to point to
the new node.
4. Increment the height attribute of the Stack class by
1.
Algorithm for push Method

The push method performs the following steps:

1. Create a New Node:


○ A new Node object is created with the given value.
○ This new node will be added to the top of the stack.
2. Check if the Stack is Empty:
○ If self.height is 0, it means the stack is currently empty.
■ In this case, set self.top to the new_node.
○ Otherwise, if the stack is not empty:
■ Set the next pointer of new_node to the current top node
(self.top). This links the new node to the existing stack.
■ Update self.top to point to the new_node, making it the
new top of the stack.
3. Increment the Stack Height:
○ Increase self.height by 1 to reflect the addition of a new
element.

def push(self, value):


new_node = Node(value) # Step 1: Create a new node with
the given value
if self.height == 0: # Step 2: Check if the stack is empty
self.top = new_node # If empty, set the new node as the
top
else:
new_node.next = self.top # Link new node to the current
top node
self.top = new_node # Set new node as the new top
self.height += 1 # Step 3: Increment the stack height
Stack:Pop
Implement the pop method for the Stack class that removes the
top node from the stack and returns it.

The method should perform the following tasks:

1. If the stack is empty (i.e., the height is 0), return None.


2. Store a reference to the current top node in a temporary
variable, temp.
3. Update the top attribute of the Stack class to point to the
next node in the stack.
4. Set the next attribute of the removed node (stored in the
temporary variable) to None.
5. Decrement the height attribute of the Stack class by 1.
6. Return the removed node (stored in the temporary variable).
Algorithm for pop Method

The pop method performs the following steps:

1. Check if the Stack is Empty:


○ If self.height is 0, it means the stack has no
elements to remove.
○ In this case, return None to indicate that the stack is
empty.
2. Remove the Top Node:
○ If the stack is not empty:
■ Store the current top node (self.top) in a
temporary variable temp. This will allow us to
return it later.
■ Update self.top to point to the next node in the
stack (self.top.next). This effectively
removes the current top node from the stack.
■ Set temp.next to None to fully detach this node
from the stack.
3. Decrement the Stack Height:
○ Decrease self.height by 1 to reflect the removal of
one node from the stack.
4. Return the Removed Node:
○ Return the temp variable, which contains the removed
node.
def pop(self):
if self.height==0:
return None
else:
temp=self.top
self.top=self.top.next
temp.next=None
self.height-=1
return temp
In Python, a stack can be efficiently implemented using a list,
which allows us to take advantage of Python's built-in list
operations to handle stack functionality (such as adding or
removing elements).
Key Characteristics of a 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 List for Stack Implementation

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).

Stack Class Implementation Using List

Here is a step-by-step implementation of the stack using Python lists.

python
Copy code
class Stack:
def __init__(self):
self.stack = [] # Step 1: Initialize an empty list to
represent the stack

Step 1: Initialize the Stack

The __init__ method creates 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

Algorithm for push:

1. Use append() to add value to the end of the list, which is the top of the stack.

Implementing the pop Method

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

Algorithm for pop:

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.

Implementing the peek Method

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

Algorithm for peek:

1. Check if the stack is empty.


2. If empty, return None.
3. If not empty, return the last element in the list (self.stack[-1]) without removing it.

Implementing the isEmpty Method

The isEmpty method checks whether the stack is empty.

python
Copy code
def isEmpty(self):
return len(self.stack) == 0 # Return True if stack length is
0, else False

Algorithm for isEmpty:

1. Check if the length of the stack list is 0.


2. Return True if it is 0, otherwise return False.

Full Stack Implementation

Here's the complete stack class using a list in Python:

python
Copy code
class Stack:
def __init__(self):
self.stack = [] # Initialize an empty list for
the stack

def push(self, value):


self.stack.append(value) # Add the value to the top of 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

Let's look at an example to understand how this stack implementation works:

python
Copy code
my_stack = Stack() # Initialize an empty stack

my_stack.push(4) # Stack becomes [4]


my_stack.push(7) # Stack becomes [4, 7]
my_stack.push(9) # Stack becomes [4, 7, 9]

print(my_stack.pop()) # Output: 9, Stack becomes [4, 7]


print(my_stack.peek()) # Output: 7, Stack remains [4, 7]
print(my_stack.isEmpty()) # Output: False

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.

Advantages of Using a List for Stack

● 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.

You might also like