forked from super30admin/PreCourse-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExercise_3_Solution.py
67 lines (44 loc) · 1.49 KB
/
Exercise_3_Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#Time Complexity : O(n)
#Space Complexity : O(n)
#Did this code successfully run on Leetcode : yes
#Any problem you faced while coding this : while removing the node.
#Your code here along with comments explaining your approach
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):
self.head = None
def append(self, data):
appendNode = ListNode(data)
if not self.head:
self.head = appendNode
#Iterating to the linked list
currentNode = self.head
while currentNode.next != None:
currentNode = currentNode.next
currentNode.next = appendNode
def find(self, key):
current = self.head
while current:
if current.data == key:
return True
current = current.next
return False
def remove(self, key):
currentNode = self.head
previousNode = None
while currentNode:
if currentNode.data == key:
if previousNode:
previousNode.next = currentNode.next
else:
self.head = currentNode.next
return True
previousNode = currentNode
currentNode = currentNode.next
return False