From 8d05fa14333a42d451d2d36b600c6c5a4b3459c2 Mon Sep 17 00:00:00 2001 From: Vishal kumar M G Date: Tue, 2 Jun 2026 20:59:53 -0500 Subject: [PATCH] PreCourse 1 complete --- Exercise_1.py | 13 +++++++++---- Exercise_2.py | 9 +++++++++ Exercise_3.py | 30 +++++++++++++++++++++++++++++- 3 files changed, 47 insertions(+), 5 deletions(-) diff --git a/Exercise_1.py b/Exercise_1.py index 532833f5d..57dea2d1b 100644 --- a/Exercise_1.py +++ b/Exercise_1.py @@ -2,20 +2,25 @@ 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 self.stack == [] def push(self, item): + self.stack.append(item) def pop(self): - + return self.stack.pop() def peek(self): - + 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..ead479ade 100644 --- a/Exercise_2.py +++ b/Exercise_2.py @@ -6,10 +6,19 @@ def __init__(self, data): class Stack: def __init__(self): + self.stack = Node(None) def push(self, data): + new_node = Node(data) + new_node.next = self.stack + self.stack = new_node def pop(self): + if self.stack.data is None: + return None + popped_data = self.stack.data + self.stack = self.stack.next + return popped_data a_stack = Stack() while True: diff --git a/Exercise_3.py b/Exercise_3.py index a5d466b59..fef0bd935 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): @@ -10,6 +12,7 @@ def __init__(self): Create a new singly-linked list. Takes O(1) time. """ + self.node = ListNode() self.head = None def append(self, data): @@ -17,16 +20,41 @@ def append(self, data): Insert a new element at the end of the list. Takes O(n) time. """ - + new_node = ListNode(data) + if not self.head: + self.head = new_node + else: + current = self.head + while current.next: + current = current.next + current.next = new_node + def find(self, key): """ Search for the first element with `data` matching `key`. Return the element or `None` if not found. Takes O(n) time. """ + current = self.head + while current: + 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. """ + current = self.head + previous = None + while current: + if current.data == key: + if previous: + previous.next = current.next + else: + self.head = current.next + return + previous = current + current = current.next \ No newline at end of file