forked from thundergolfer/interview-with-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked-list.py
More file actions
67 lines (54 loc) · 1.62 KB
/
linked-list.py
File metadata and controls
67 lines (54 loc) · 1.62 KB
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
import unittest
class LinkedList(object):
def __init__(self):
self.length = 0
self.head = None
def insertStart(self, cargo):
node = Node(cargo)
node.next = self.head
self.head = node
self.length += 1
def remove(self, elem):
if self.head == None:
return False # elem was not found
elif self.head.cargo == elem:
self.head = self.head.next
self.length -= 1
return True
else:
prevNode = self.head
currNode = self.head.next
while currNode:
if currNode.cargo == elem:
prevNode.next = currNode.next # link over the node to delete
self.length -= 1
return True
return False # elem was not found
def printBackward(self):
print("[", end="")
if self.head != None:
self.head.printBackward()
print("]")
class Node(object):
def __init__(self, cargo=None, next=None):
self.cargo = cargo
self.next = next
def __str__(self):
return str(self.cargo)
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
if not self.cargo == other.cargo:
return False
return True
class Test_LinkedList(unittest.TestCase):
def setUp(self):
pass
def test_linked_list_one(self):
ll = LinkedList()
ll.insertStart(5)
ll.insertStart(10)
self.assertEqual( ll.length, 2 )
self.assertTrue( ll.remove(10) )
if __name__ == '__main__':
unittest.main()