-
Notifications
You must be signed in to change notification settings - Fork 0
/
0.linkList.py
104 lines (91 loc) · 2.98 KB
/
0.linkList.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# This is an input class. Do not edit.
class Node:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
# Feel free to add new properties and methods to the class.
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def setHead(self, node):
# Write your code here.
if self.head is None:
self.head = node
self.tail = node
else:
self.insertAfter(self.tail, node)
def setTail(self, node):
# Write your code here.
if self.tail is None:
self.head = node
self.tail = node
else:
self.insertAfter(self.tail, node)
def insertBefore(self, node, nodeToInsert):
# Write your code here.
if nodeToInsert == self.head and nodeToInsert == self.tail:
return
self.remove(nodeToInsert)
nodeToInsert.next = node
nodeToInsert.prev = node.prev
if node.prev is None:
self.head = nodeToInsert
else:
node.prev.next = nodeToInsert
node.prev = nodeToInsert
def insertAfter(self, node, nodeToInsert):
# Write your code here.
if nodeToInsert == self.head and nodeToInsert == self.tail:
return
self.remove(nodeToInsert)
nodeToInsert.prev = node
nodeToInsert.next = node.next
if node.next is None:
self.tail = nodeToInsert
else:
node.next.prev = nodeToInsert
node.next = nodeToInsert
def insertAtPosition(self, position, nodeToInsert):
# Write your code here.
if position == 1:
self.setHead(nodeToInsert)
return
node = self.head
currentPosition = 1
while node is not None and currentPosition < position:
node = node.next
currentPosition += 1
if node is not None:
self.insertBefore(node, nodeToInsert)
else:
self.setTail(nodeToInsert)
def removeNodesWithValue(self, value):
# Write your code here.
currentNode = self.head
while currentNode != None:
nextNode = currentNode.next
if currentNode.value == value:
self.remove(currentNode)
currentNode = nextNode
def remove(self, node):
# Write your code here.
if node == self.head:
self.head = node.next
if node == self.tail:
self.tail = node.prev
if node.prev is not None:
node.prev.next = node.next
if node.next is not None:
node.next.prev = node.prev
node.prev = None
node.next = None
def containsNodeWithValue(self, value):
# Write your code here.
currentNode = self.head
while currentNode != None:
if currentNode.value == value:
return True
currentNode = currentNode.next
return False