-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_linkedlist.py
More file actions
64 lines (50 loc) · 1.45 KB
/
reverse_linkedlist.py
File metadata and controls
64 lines (50 loc) · 1.45 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
"""Reverse a linked list"""
class LinkedList:
"""Represents a singly-linked list"""
def __init__(self, list_):
"""Build a linked list from the provided list
Sets an attribute `head` with points to the first node of the
linked list"""
self._head = None
current = None
for i in list_:
if self._head is None:
self._head = self.Node(i)
current = self._head
else:
current.next = self.Node(i)
current = current.next
def _items(self):
"""Generates the linked list values in order"""
node = self._head
while node:
yield node.value
node = node.next
def reverse(self):
current = self._head
prev = None
while current:
nxt = current.next
current.next = prev
prev = current
current = nxt
self._head = prev
def __iter__(self):
return self._items()
class Node:
def __init__(self, value):
self.value = value
self.next = None
if __name__ == "__main__":
ll = LinkedList([])
assert list(ll) == []
ll.reverse()
assert list(ll) == []
ll = LinkedList([1])
assert list(ll) == [1]
ll.reverse()
assert list(ll) == [1]
ll = LinkedList([1, 2, 'a'])
assert list(ll) == [1, 2, 'a']
ll.reverse()
assert list(ll) == ['a', 2, 1]