diff --git a/Exercise_1.py b/Exercise_1.py index 532833f5d..64aae4e4a 100644 --- a/Exercise_1.py +++ b/Exercise_1.py @@ -1,20 +1,29 @@ 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 __init__(self): + self.ls=[] + + def isEmpty(self): + return len(self.ls)==0 - def push(self, item): + def push(self, item): + self.ls.append(item) - def pop(self): - + def pop(self): + if self.isEmpty(): + return None + return self.ls.pop() - def peek(self): + def peek(self): + if len(self.ls)>0: + return self.ls[-1] + return None - def size(self): + def size(self): + return len(self.ls) - def show(self): + def show(self): + return self.ls s = myStack() diff --git a/Exercise_2.py b/Exercise_2.py index b11492215..3193c0d0d 100644 --- a/Exercise_2.py +++ b/Exercise_2.py @@ -6,10 +6,20 @@ def __init__(self, data): class Stack: def __init__(self): + self.head=Node(-1) def push(self, data): - + node=Node(data) + node.next=self.head.next + self.head.next=node def pop(self): + if self.head.next is None: + return None + q=self.head.next + self.head.next=q.next + return q.data + + a_stack = Stack() while True: diff --git a/Exercise_3.py b/Exercise_3.py index a5d466b59..ecf36a310 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!=None: + curr=curr.next + curr.next=ListNode(data) def find(self, key): """ @@ -24,9 +33,28 @@ def find(self, key): `key`. Return the element or `None` if not found. Takes O(n) time. """ + curr=self.head + while curr!=None: + if curr.data==key: + return key + curr = curr.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 + curr = self.head + while curr.next is not None: + if curr.next.data == key: + curr.next = curr.next.next + return + curr = curr.next