diff --git a/Exercise_1.py b/Exercise_1.py index 532833f5d..5da7108e3 100644 --- a/Exercise_1.py +++ b/Exercise_1.py @@ -1,20 +1,42 @@ +# Time Complexity : +# isEmpty: O(1) +# push: O(1) +# pop: O(1) +# peek: O(1) +# size: O(1) +# show: O(n) +# Space Complexity : Space Complexity is O(n) +# Did this code successfully run on Leetcode : Solved minstack successfully, The minStack needs to be traversed with the help of +# Any problem you faced while coding this : None. class myStack: #Please read sample.java file before starting. #Kindly include Time and Space complexity at top of each file 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 self.isEmpty(): + return print("Stack Empty") + return self.stack.pop() def peek(self): + if self.isEmpty(): + return print("Stack Empty") + return self.stack[-1] + def size(self): + return len(self.stack) def show(self): + return self.stack s = myStack() diff --git a/Exercise_2.py b/Exercise_2.py index b11492215..3b5b4451f 100644 --- a/Exercise_2.py +++ b/Exercise_2.py @@ -1,4 +1,8 @@ - +# Time Complexity : +# push: O(1) +# pop: O(1) +# Space Complexity : O(n) +# Any problem you faced while coding this : None class Node: def __init__(self, data): self.data = data @@ -6,10 +10,19 @@ def __init__(self, data): class Stack: def __init__(self): + self.top = None def push(self, data): + newNode = Node(data) + newNode.next = self.top + self.top = newNode def pop(self): + if self.top is None: + return None + res = self.top.data + self.top = self.top.next + return res a_stack = Stack() while True: diff --git a/Exercise_3.py b/Exercise_3.py index a5d466b59..4475b86c4 100644 --- a/Exercise_3.py +++ b/Exercise_3.py @@ -1,8 +1,14 @@ +# Time Complexity : +# Space Complexity : +# Did this code successfully run on Leetcode : +# Any problem you faced while coding this : 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 +23,12 @@ def append(self, data): Insert a new element at the end of the list. Takes O(n) time. """ + New_Node = ListNode(data) + curr = self.head + while curr.next: + curr = curr.next + + curr.next = New_Node def find(self, key): """ @@ -24,9 +36,24 @@ def find(self, key): `key`. Return the element or `None` if not found. Takes O(n) time. """ + curr = self.head + + while curr.next: + 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 + + while curr.next and curr.next.next: + if curr.next.val == key: + curr.next = curr.next.next + break + curr = curr.next