diff --git a/Exercise_1.py b/Exercise_1.py index 532833f5d..398476e97 100644 --- a/Exercise_1.py +++ b/Exercise_1.py @@ -1,21 +1,35 @@ +# Time Complexity : O(1) for all operations +# Space Complexity : O(n) - n is size +# Did this code successfully run on Leetcode : Ran on terminal +# Any problem you faced while coding this : NA + class myStack: #Please read sample.java file before starting. #Kindly include Time and Space complexity at top of each file def __init__(self): + self.myStack=[] def isEmpty(self): + return len(self.myStack)==0 def push(self, item): + self.myStack.append(item) def pop(self): - + if self.isEmpty(): + return "Stack is Empty" + return self.myStack.pop() def peek(self): - + if self.isEmpty(): + return "Stack is Empty" + return self.myStack[-1] + def size(self): + return len(self.myStack) def show(self): - + return self.myStack s = myStack() s.push('1') diff --git a/Exercise_2.py b/Exercise_2.py index b11492215..ec6f5f319 100644 --- a/Exercise_2.py +++ b/Exercise_2.py @@ -1,3 +1,5 @@ +# Time Complexity : O(1) for all operations +# Space Complexity : O(n) - n is size class Node: def __init__(self, data): @@ -6,10 +8,20 @@ def __init__(self, data): class Stack: def __init__(self): + self.top = None def push(self, data): + new_item = Node(data) + new_item.next = self.top + + self.top = new_item def pop(self): + if self.top == None: + return None + popped = self.top + self.top = popped.next + return popped.data a_stack = Stack() while True: diff --git a/Exercise_3.py b/Exercise_3.py index a5d466b59..e5bb64179 100644 --- a/Exercise_3.py +++ b/Exercise_3.py @@ -3,6 +3,8 @@ 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,6 +19,17 @@ def append(self, data): Insert a new element at the end of the list. Takes O(n) time. """ + new_item = ListNode(data) + curr = self.head + #If empty set the head + if curr is None: + self.head = new_item + return + + #Traverse to the end and point last element's next to the new node + while curr.next: + curr = curr.next + curr.next = new_item def find(self, key): """ @@ -24,9 +37,31 @@ def find(self, key): `key`. Return the element or `None` if not found. Takes O(n) time. """ + curr = self.head + # Traverse until data is found + while curr: + if curr.data == key: + return curr + curr=curr.next + return None def remove(self, key): """ Remove the first occurrence of `key` in the list. Takes O(n) time. """ + curr = self.head + if curr is None: + return + if curr.data == key: + self.head = curr.next + return + #Traverse to find the element but keep the poointer one step back so we can change the next pointer + while curr.next: + if curr.next.data == key: + curr.next = curr.next.next + return + curr=curr.next + return None + +