-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedlist.py
124 lines (85 loc) · 2.8 KB
/
linkedlist.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# Linked list with Node/LinkedList classes
class Node(object):
"""Node in a linked list."""
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return "<Node %s>" % self.data
class LinkedList(object):
"""Linked List using head and tail."""
def __init__(self):
self.head = None
self.tail = None
def add_node(self, data):
"""Add node with data to end of list."""
new_node = Node(data)
if self.head is None:
self.head = new_node
if self.tail is not None:
self.tail.next = new_node
self.tail = new_node
def remove_node_by_index(self, index):
"""Remove node with given index."""
prev = None
node = self.head
i = 0
while (node is not None) and (i < index):
prev = node
node = node.next
i += 1
if prev is None:
self.head = node.next
else:
prev.next = node.next
def find_node(self, data):
"""Is a matching node in the list?"""
current = self.head
while current is not None:
if current.data == data:
return True
current = current.next
return False
def print_list(self):
"""Print all items in the list::
>>> ll = LinkedList()
>>> ll.add_node('dog')
>>> ll.add_node('cat')
>>> ll.add_node('fish')
>>> ll.print_list()
dog
cat
fish
"""
# FIXME
# Start at the first node of the LL
# If this node is not None, then print the node's data
# Reset the node to the next node
current = self.head
while current is not None:
print current.data
current = current.next
def get_node_by_index(self, idx):
"""Return a node with the given index::
>>> ll = LinkedList()
>>> ll.add_node('dog')
>>> ll.add_node('cat')
>>> ll.add_node('fish')
>>> ll.get_node_by_index(0)
<Node dog>
>>> ll.get_node_by_index(2)
<Node fish>
"""
# FIXME
# If not an empty LL, then node at self.head will be index 0
# Every node after should increment the index
# If given index matches this index, return the node
node = self.head
i = 0
while node is not None:
if i == idx:
return node
else:
i += 1
node = node.next
# Originally, had some other variations but tested out in interactive mode and the code didn't work, so had to try again and eventually came up with this working solution