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

Practical 4-Stack Stack Datastructure

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

Practical 4-Stack Stack Datastructure

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

Practical-4: stack data structure

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle,
meaning the last element added to the stack is the first one to be removed. Think of it as a
stack of plates: you can only take the top plate off the stack, and when you add a plate, you
place it on top.
Key Operations:
1. Push: Add an element to the top of the stack.
2. Pop: Remove the top element from the stack.
3. Peek/Top: View the top element without removing it.
4. isEmpty: Check if the stack is empty.
5. isFull (optional, for fixed-size stacks): Check if the stack is full.

Example of Stack Operations:


# Implementing a simple stack using a list
class Stack:
def __init__(self):
self.stack = []
# Push operation
def push(self, item):
self.stack.append(item)
# Pop operation
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty"
# Peek operation
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
return "Stack is empty"

1
# Check if stack is empty
def is_empty(self):
return len(self.stack) == 0
# Example usage
s = Stack()
s.push(1)
s.push(2)
s.push(3)
print(s.peek()) # Output: 3
print(s.pop()) # Output: 3
print(s.pop()) # Output: 2
print(s.is_empty()) # Output: False
print(s.pop()) # Output: 1
print(s.is_empty()) # Output: True

EXPLANATION OF YOUR STACK IMPLEMENTATION:


class Stack:
 Defines a class named Stack. This class will encapsulate the stack's behavior and
properties.
def __init__(self):
self.stack = []
 __init__ method: This is the constructor method that initializes a new instance of the
class.
 self.stack = []: Initializes an empty list to hold the stack's elements.
def push(self, item):
self.stack.append(item)
 push method: This method adds an item to the top of the stack.
 self.stack.append(item): Uses the append method to add the specified item to the end
of the list (top of the stack).
def pop(self):

2
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty"
 pop method: This method removes and returns the top item from the stack.
 if not self.is_empty(): Checks if the stack is not empty before attempting to pop. This
prevents errors from popping from an empty stack.
 return self.stack.pop(): If the stack has elements, it uses the pop method of the list to
remove and return the last item.
 else: return "Stack is empty": If the stack is empty, it returns a message indicating
that.
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
return "Stack is empty"
 peek method: This method returns the top item of the stack without removing it.
 if not self.is_empty(): Checks if the stack is not empty.
 return self.stack[-1]: Returns the last item in the list (the top of the stack).
 else: return "Stack is empty": Returns a message if the stack is empty.
def is_empty(self):
return len(self.stack) == 0
 is_empty method: This method checks if the stack is empty.
 return len(self.stack) == 0: Returns True if the length of the stack is zero, indicating
it's empty; otherwise, it returns False.
Example Usage:
s = Stack()
 Creates an instance of the Stack class.
s.push(1)
s.push(2)
s.push(3)
 Pushes three items (1, 2, 3) onto the stack.

3
print(s.peek()) # Output: 3
 Prints the top item of the stack without removing it. Expected output is 3.
print(s.pop()) # Output: 3
 Removes and prints the top item of the stack. Expected output is 3.
print(s.pop()) # Output: 2
 Removes and prints the next top item. Expected output is 2.

print(s.is_empty()) # Output: False


 Checks if the stack is empty and prints the result. Expected output is False (since
there are still elements).
print(s.pop()) # Output: 1
 Removes and prints the last item. Expected output is 1.
python
Copy code
print(s.is_empty()) # Output: True
 Checks if the stack is empty again. Expected output is True (since the stack is now
empty).
This implementation effectively captures the essential operations of a stack and demonstrates
how to manage elements in a LIFO manner.
If we want to implement a stack using only the push and pop operations, here's a minimal
example focusing strictly on these two methods.
Python Example Using Only push and pop:
class Stack:
def __init__(self):
self.stack = []
# Push operation: Adds an element to the stack
def push(self, item):
self.stack.append(item)
# Pop operation: Removes and returns the top element of the stack
def pop(self):
if not self.is_empty():
return self.stack.pop()

4
else:
return "Stack is empty"
# Check if the stack is empty (helper method for pop)
def is_empty(self):
return len(self.stack) == 0

# Example usage
s = Stack()
s.push(10)
s.push(20)
s.push(30)

print(s.pop()) # Output: 30
print(s.pop()) # Output: 20
print(s.pop()) # Output: 10
print(s.pop()) # Output: Stack is empty
Key Points:
 push(item): Adds an item to the top of the stack.
 pop (): Removes and returns the top item from the stack. If the stack is empty, it
handles the underflow case by checking with is_empty().

Push 10 words onto a stack, pop 6 of them, and print


the remaining words without using a for loop:
class Stack:
def __init__(self):
self.stack = []
# Push operation
def push(self, item):
self.stack.append(item)

5
# Pop operation
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty"

# Check if the stack is empty


def is_empty(self):
return len(self.stack) == 0

# Example usage
s = Stack()

# Push 10 words onto the stack


s.push("apple")
s.push("banana")
s.push("cherry")
s.push("date")
s.push("elderberry")
s.push("fig")
s.push("grape")
s.push("honeydew")
s.push("kiwi")
s.push("lemon")

# Pop 6 words from the stack


s.pop() # 1st pop
s.pop() # 2nd pop
s.pop() # 3rd pop

6
s.pop() # 4th pop
s.pop() # 5th pop
s.pop() # 6th pop

# Print the remaining words in the stack


print("Remaining words in the stack:", s.stack)
Output:
Remaining words in the stack: ['apple', 'banana', 'cherry', 'date']
Explanation:
1. Each push adds a word to the stack.
2. Each pop removes the top word from the stack, done explicitly without loops.
3. Finally, the remaining words are printed.

Here's how you can push 10 words onto a stack, pop 6 of them,
and print the remaining words in the stack using for loop:

class Stack:
def __init__(self):
self.stack = []
# Push operation
def push(self, item):
self.stack.append(item)
# Pop operation
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty"

# Check if the stack is empty

7
def is_empty(self):
return len(self.stack) == 0
# Example usage
s = Stack()
# Push 10 words onto the stack
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew",
"kiwi", "lemon"]
for word in words:
s.push(word)

# Pop 6 words from the stack


for _ in range(6):
s.pop()
# Print the remaining words in the stack
print("Remaining words in the stack:", s.stack)
Output:
Remaining words in the stack: ['apple', 'banana', 'cherry', 'date']
Explanation:
1. We pushed 10 words onto the stack.
2. We popped 6 words off the stack.
3. The remaining words after popping are printed.

Here’s an implementation of a stack that captures 10 numbers and demonstrates the


key operations: push, pop, peek, isEmpty, and an optional isFull method for fixed-size
stacks.
Python Implementation
class Stack:
def __init__(self, size=10):
self.stack = []
self.size = size # Maximum size of the stack

8
# Push operation
def push(self, item):
if not self.is_full():
self.stack.append(item)
print(f"Pushed: {item}")
else:
print("Stack is full. Cannot push.")

# Pop operation
def pop(self):
if not self.is_empty():
popped_item = self.stack.pop()
print(f"Popped: {popped_item}")
return popped_item
else:
print("Stack is empty. Cannot pop.")

# Peek operation
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
print("Stack is empty. No top element.")

# Check if the stack is empty


def is_empty(self):
return len(self.stack) == 0

# Check if the stack is full


def is_full(self):

9
return len(self.stack) == self.size

# Example usage
s = Stack()

# Capture 10 numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Push numbers onto the stack


for number in numbers:
s.push(number)

# Perform operations
print("Top element:", s.peek()) # View the top element

# Pop 5 elements
for _ in range(5):
s.pop()
# Check if the stack is empty or full
print("Is the stack empty?", s.is_empty())
print("Is the stack full?", s.is_full())
# View remaining elements
print("Remaining elements in the stack:", s.stack)
Explanation of Key Operations:
1. Push: The push method adds an item to the stack if it’s not full.
2. Pop: The pop method removes the top item from the stack if it’s not empty.
3. Peek: The peek method returns the top item without removing it.
4. isEmpty: The is_empty method checks if the stack has no elements.
5. isFull: The is_full method checks if the stack has reached its maximum size.
Example Output:

10
When you run this code, the output will reflect the operations performed, such as which
numbers are pushed and popped, and the status of the stack.

Applications of Stacks:
 Backtracking algorithms (e.g., maze-solving)
 Undo/Redo functionality in text editors
 Expression evaluation (e.g., infix to postfix conversion)
 Call stack in programming languages

11

You might also like