Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions Question 1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Question 1
class Stack:
def __init__(self):
self.items = []

def push(self, item):
self.items.append(item)

def pop(self):
if not self.is_empty():
return self.items.pop()
raise IndexError("pop from an empty stack")

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

def peek(self):
if not self.is_empty():
return self.items[-1]
raise IndexError("peek from an empty stack")

def reverse_string(s: str) -> str:
stack = Stack()

# Push all characters of the string onto the stack
for char in s:
stack.push(char)

# Pop all characters from the stack and build the reversed string
reversed_str = ''
while not stack.is_empty():
reversed_str += stack.pop()

return reversed_str

def main():
# Prompt user for input
user_input = input("Enter a string to reverse: ")

# Reverse the string
reversed_string = reverse_string(user_input)

# Output the reversed string
print(f"Reversed string: {reversed_string}")

# Run the main function if this script is executed
if __name__ == "__main__":
main()


25 changes: 25 additions & 0 deletions Question 2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Question 2
class QueueWithStacks:
def __init__(self):
self.stack1 = [] # Stack used for enqueue operations
self.stack2 = [] # Stack used for dequeue operations

def enqueue(self, x: int):
# Push the element onto stack1
self.stack1.append(x)

def dequeue(self) -> int:
# If stack2 is empty, transfer elements from stack1 to stack2
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())

# If stack2 is still empty, the queue is empty and we cannot dequeue
if not self.stack2:
raise IndexError("dequeue from an empty queue")

# Pop the top element from stack2
return self.stack2.pop()



35 changes: 35 additions & 0 deletions Question 3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Question 3
class Node:
def __init__(self, value: int):
self.value = value
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def append(self, value: int):
"""Append a new node with the given value to the end of the list."""
new_node = Node(value)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node

def find_max(self) -> int:
"""Find the maximum value in the linked list."""
if not self.head:
raise ValueError("The linked list is empty")

current = self.head
max_value = current.value

while current:
if current.value > max_value:
max_value = current.value
current = current.next

return max_value