diff --git a/Exercise_1.py b/Exercise_1.py index 532833f5d..ff1de95a2 100644 --- a/Exercise_1.py +++ b/Exercise_1.py @@ -2,19 +2,30 @@ 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 "Stack is Empty" + + return self.stack.pop() def peek(self): + if self.isEmpty(): + return "Stack is 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..407a22bfe 100644 --- a/Exercise_2.py +++ b/Exercise_2.py @@ -6,10 +6,25 @@ def __init__(self, data): class Stack: def __init__(self): + self.head = None def push(self, data): + if self.head == None: + self.head = Node(data) + else: + nw = Node(data) + nw.next = self.head + self.head = nw + def pop(self): + if self.head is not None: + ppn = self.head + self.head = self.head.next + ppn.next = None + return ppn.data + else: + return None a_stack = Stack() while True: diff --git a/Exercise_3.py b/Exercise_3.py index a5d466b59..dba3a3c1a 100644 --- a/Exercise_3.py +++ b/Exercise_3.py @@ -2,7 +2,12 @@ class ListNode: """ A node in a singly-linked list. """ - def __init__(self, data=None, next=None): + + def __init__(self, data, next=None): + self.data = data + self.next = next + + class SinglyLinkedList: def __init__(self): @@ -13,12 +18,33 @@ def __init__(self): self.head = None def append(self, data): + + if self.head == None: + self.head = ListNode(data) + return + + curr = self.head + while curr.next: + curr = curr.next + curr.next = ListNode(data) + + + + """ Insert a new element at the end of the list. Takes O(n) time. """ def find(self, key): + + curr = self.head + while (curr): + if (curr.data == key): + return curr + + curr = curr.next + return None """ Search for the first element with `data` matching `key`. Return the element or `None` if not found. @@ -26,7 +52,34 @@ def find(self, key): """ def remove(self, key): + if self.head and self.head.data == key: + temp = self.head + self.head = self.head.next + temp.next = None + return + + curr = self.head + while curr and curr.next: + if (curr.next.data == key): + temp = curr.next + curr.next = curr.next.next + temp.next = None + return + curr = curr.next + return None """ Remove the first occurrence of `key` in the list. Takes O(n) time. """ + def print_list(self): + curr = self.head + + if curr is None: + print("List is empty") + return + + while curr: + print(curr.data, end=" -> ") + curr = curr.next + print("None") +