diff --git a/Exercise_1.py b/Exercise_1.py index 532833f5d..1f25ab0ff 100644 --- a/Exercise_1.py +++ b/Exercise_1.py @@ -1,21 +1,31 @@ +# Time Complexity: O(1) for push, pop, peek; O(n) for show +# Space Complexity: O(n) for storing stack elements + class myStack: - #Please read sample.java file before starting. - #Kindly include Time and Space complexity at top of each file - def __init__(self): - - def isEmpty(self): - - def push(self, item): - - def pop(self): - - - def peek(self): - - def size(self): - - def show(self): - + def __init__(self): + self.stack = [] + + def isEmpty(self): + return len(self.stack) == 0 + + def push(self, item): + self.stack.append(item) + + def pop(self): + if not self.isEmpty(): + return self.stack.pop() + return "Stack is empty" + + def peek(self): + if not self.isEmpty(): + return self.stack[-1] + return "Stack is empty" + + def size(self): + return len(self.stack) + + def show(self): + return self.stack s = myStack() s.push('1') diff --git a/Exercise_2.py b/Exercise_2.py index b11492215..5a0b10f57 100644 --- a/Exercise_2.py +++ b/Exercise_2.py @@ -6,10 +6,19 @@ def __init__(self, data): class Stack: def __init__(self): - + self.top = None + def push(self, data): - + new_node = Node(data) + new_node.next = self.top + self.top = new_node + def pop(self): + if self.top is None: + return None + popped_data = self.top.data + self.top = self.top.next + return popped_data a_stack = Stack() while True: diff --git a/Exercise_3.py b/Exercise_3.py index a5d466b59..9ff8a20f5 100644 --- a/Exercise_3.py +++ b/Exercise_3.py @@ -3,7 +3,9 @@ class ListNode: A node in a singly-linked list. """ def __init__(self, data=None, next=None): - + self.data = data + self.next = next + class SinglyLinkedList: def __init__(self): """ @@ -17,16 +19,41 @@ def append(self, data): Insert a new element at the end of the list. Takes O(n) time. """ - + new_node = ListNode(data) + if not self.head: + self.head = new_node + return + current = self.head + while current.next: + current = current.next + current.next = new_node + def find(self, key): """ Search for the first element with `data` matching `key`. Return the element or `None` if not found. Takes O(n) time. """ - + current = self.head + while current: + if current.data == key: + return current + current = current.next + return None + def remove(self, key): """ Remove the first occurrence of `key` in the list. Takes O(n) time. """ + current = self.head + previous = None + while current: + if current.data == key: + if previous: + previous.next = current.next + else: + self.head = current.next + return + previous = current + current = current.next