From 3e517482d8b630626aede6503e8aab4bf9527039 Mon Sep 17 00:00:00 2001 From: Akash Diyora Date: Sat, 18 Jan 2025 23:50:29 -0500 Subject: [PATCH] Done PreCourse-1 --- Exercise_1.py | 21 +++++++++++++++++++++ Exercise_2.py | 14 ++++++++++++-- Exercise_3.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+), 2 deletions(-) diff --git a/Exercise_1.py b/Exercise_1.py index 532833f5d..61304b726 100644 --- a/Exercise_1.py +++ b/Exercise_1.py @@ -2,19 +2,40 @@ class myStack: #Please read sample.java file before starting. #Kindly include Time and Space complexity at top of each file def __init__(self): + self.value = [] def isEmpty(self): + return len(self.value) == 0 def push(self, item): + self.value.append(item) + def pop(self): + if not self.isEmpty(): + return self.value.pop() + + return "Stake is empty!" + def peek(self): + if not self.isEmpty(): + return self.value[-1] + + return "Stake is empty!" + + def size(self): + return len(self.value) + def show(self): + if self.isEmpty(): + return "Sorry,there is No items in the list" + return self.value + s = myStack() diff --git a/Exercise_2.py b/Exercise_2.py index b11492215..3ac0435b1 100644 --- a/Exercise_2.py +++ b/Exercise_2.py @@ -6,10 +6,20 @@ def __init__(self, data): class Stack: def __init__(self): - + self.top = None + def push(self, data): - + new_node = Node(data) + new_node.next = self.top + self.top = new_node + def pop(self): + if self.top is None: + return None + + popped_data = self.top.data + self.top = self.top.next + return popped_data a_stack = Stack() while True: diff --git a/Exercise_3.py b/Exercise_3.py index a5d466b59..fc37e428c 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 = None class SinglyLinkedList: def __init__(self): @@ -13,10 +15,25 @@ def __init__(self): self.head = None def append(self, data): + + new_node = ListNode(data) + + if self.head is None: + self.head = new_node + return + + current = self.head + if current.next is not None: + current = current.next + + current.next = new_node + + """ Insert a new element at the end of the list. Takes O(n) time. """ + def find(self, key): """ @@ -24,9 +41,38 @@ def find(self, key): `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 + + if current is None: + return None + + if current.data == key: + self.head = current.next + current = None + return + + while current: + if current.data == key: + previous.next = current.next + current = None + previous = current + current = current.next + return None +