-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingly_linked_list.py
More file actions
87 lines (75 loc) · 2.24 KB
/
Copy pathsingly_linked_list.py
File metadata and controls
87 lines (75 loc) · 2.24 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class Node:
""" A singly-linked node. """
def __init__(self, data = None):
self.data = data
self.next = None
class SinglyLinkedList:
""" A singly-linked List. """
def __init__(self):
""" Create an empty list. """
self.tail = None
self.head = None
self.count = 0
def iter(self):
""" Iterate through the list. """
current = self.tail
while current:
val = current.data
current = current.next
yield val
def append(self, data):
""" Append an item to the list """
node = Node(data)
if self.head:
self.head.next = node
self.head = node
else:
self.tail = node
self.head = node
self.count += 1
def delete(self, data):
""" Delete a node from the list """
current = self.tail
prev = self.tail
while current:
if current.data == data:
if current == self.tail:
self.tail = current.next
else:
prev.next = current.next
self.count -= 1
return
prev = current
current = current.next
def search(self, data):
""" Search through the list. Return True if data is found otherwise
False. """
for node in self.iter():
if data == node:
return True
return False
def __getitem__(self, index):
if index > self.count - 1:
raise Exception("Index out of range.")
current = self.tail
for n in range(index):
current = current.next
return current.data
def __setitem__(self, index, value):
if index > self.count -1:
raise Exception("Index out of range.")
current = self.tail
for n in range(index):
current = current.next
current.data = value
words = SinglyLinkedList()
words.append('foo')
words.append('bar')
words.append('bim')
words.append('baz')
words.append('quux')
print("access by index")
print("here is a node: {}".format(words[1]))
print("modify by index")
words[4] = "Quux"
print("Modified node by index: {}".format(words[4]))