Data Structure Ideas and Solutions
Data Structure Ideas and Solutions
Question:
Implement a stack data structure using an array in a programming language of
your choice. The stack should support the following operations:
Solution (Python):
class Stack:
def __init__(self):
self.stack = []
self.stack.append(x)
def pop(self):
if not self.isEmpty():
return self.stack.pop()
else:
if not self.isEmpty():
return self.stack[-1]
else:
def isEmpty(self):
return len(self.stack) == 0
# Example usage:
stack = Stack()
stack.push(10)
stack.push(20)
print(stack.peek()) # Output: 20
print(stack.pop()) # Output: 20
print(stack.pop()) # Output: 10
Question:
Given a singly linked list, write a function to find and return the middle element. If
the list has an even number of elements, return the second middle element.
Solution (Python):
class Node:
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
new_node = Node(data)
if not self.head:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def find_middle(self):
slow_ptr = self.head
fast_ptr = self.head
while fast_ptr and fast_ptr.next:
slow_ptr = slow_ptr.next
fast_ptr = fast_ptr.next.next
# Example usage:
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(4)
ll.append(5)
print(ll.find_middle()) # Output: 3
ll.append(6)
print(ll.find_middle()) # Output: 4
Question:
Write a function to check if a given string containing parentheses is balanced. A
string is considered balanced if each opening parenthesis ( has a corresponding
closing parenthesis ) and they are correctly nested.
Solution (Python):
def is_balanced(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
return False
stack.pop()
return len(stack) == 0
# Example usage: