diff --git a/Exercise_1.py b/Exercise_1.py index 532833f5d..29ff614b1 100644 --- a/Exercise_1.py +++ b/Exercise_1.py @@ -1,20 +1,30 @@ 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): + # Please read sample.java file before starting. + # Kindly include Time and Space complexity at top of each file + def __init__(self): + self.st = [] + def isEmpty(self): + return len(self.st) == 0 - def peek(self): + def push(self, item): + self.st.append(item) - def size(self): - - def show(self): + def pop(self): + if self.isEmpty(): + return + return self.st.pop() + + def peek(self): + if self.isEmpty(): + return None + return self.st[-1] + + def size(self): + return len(self.st) + + def show(self): + return self.st s = myStack() diff --git a/Exercise_2.py b/Exercise_2.py index b11492215..1731488ca 100644 --- a/Exercise_2.py +++ b/Exercise_2.py @@ -6,11 +6,23 @@ def __init__(self, data): class Stack: def __init__(self): + self.top = None def push(self, data): + newNode = Node(data) + if self.top is None: + self.top = newNode + return + newNode.next = self.top + self.top = newNode def pop(self): - + if self.top is None: + return None + popped = self.top.data + self.top = self.top.next + return popped + a_stack = Stack() while True: #Give input as string if getting an EOF error. Give input like "push 10" or "pop" diff --git a/Exercise_3.py b/Exercise_3.py index a5d466b59..801ed812d 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,13 @@ def append(self, data): Insert a new element at the end of the list. Takes O(n) time. """ + if self.head is None: + self.head = ListNode(data) + return + curr = self.head + while curr.next: + curr = curr.next + curr.next = ListNode(data) def find(self, key): """ @@ -24,9 +33,30 @@ def find(self, key): `key`. Return the element or `None` if not found. Takes O(n) time. """ + curr = self.head + 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. """ + prev = None + curr = self.head + + while curr: + if curr.data == key: + if prev is None: + self.head = curr.next + else: + prev.next = curr.next + return True + prev = curr + curr = curr.next + + return False +