From 911cd2ac27b7493f8f6b513efd1023cc7ad8a662 Mon Sep 17 00:00:00 2001 From: Manasvi Reddy Date: Thu, 4 Jun 2026 16:05:04 -0400 Subject: [PATCH] Done PreCourse-1 --- Exercise_1.py | 20 +++++++++++++++----- Exercise_2.py | 15 ++++++++++++--- Exercise_3.py | 35 +++++++++++++++++++++++++++++++++-- 3 files changed, 60 insertions(+), 10 deletions(-) diff --git a/Exercise_1.py b/Exercise_1.py index 532833f5d..2a78ac8ef 100644 --- a/Exercise_1.py +++ b/Exercise_1.py @@ -1,21 +1,31 @@ +#Time Complexity: o(1) +# #Space Complexity:0(n) 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 None + return self.stack.pop() def peek(self): - + if self.isEmpty(): + return None + return self.stack[-1] 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..c87d5a15a 100644 --- a/Exercise_2.py +++ b/Exercise_2.py @@ -1,4 +1,5 @@ - +#Time Complexity: O(1) +#Space Complexity: O(n) class Node: def __init__(self, data): self.data = data @@ -6,10 +7,18 @@ def __init__(self, data): class Stack: def __init__(self): + self.top = None def push(self, data): - - def pop(self): + new_node=Node(data) + new_node.next=self.top + self.top=new_node +def pop(self): + if self.top is None: + return None + popitem = self.top.data + self.top=self.top.next + return popitem a_stack = Stack() while True: diff --git a/Exercise_3.py b/Exercise_3.py index a5d466b59..2f158a95e 100644 --- a/Exercise_3.py +++ b/Exercise_3.py @@ -1,9 +1,14 @@ +# Time Complexity : O(n) +# Space Complexity : O(n) + 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 +22,15 @@ def append(self, data): Insert a new element at the end of the list. Takes O(n) time. """ + new_node = ListNode(data) + if self.head is None: + self.head = new_node + return + current = self.head + while current.next is not None: + current = current.next + current.next = new_node + def find(self, key): """ @@ -24,9 +38,26 @@ def find(self, key): `key`. Return the element or `None` if not found. Takes O(n) time. """ - + current = self.head + while current is not None: + 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. """ + if self.head is None: + return + if self.head.data == key: + self.head = self.head.next + return + current = self.head + while current.next is not None: + if current.next.data == key: + current.next = current.next.next + return + current = current.next +