-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathreverse.py
More file actions
56 lines (45 loc) · 1.61 KB
/
reverse.py
File metadata and controls
56 lines (45 loc) · 1.61 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
class Node:
def __init__(self, value=None, next_node=None):
# the value at this linked list node
self.value = value
# reference to the next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
# set this node's next_node reference to the passed in node
self.next_node = new_next
class LinkedList:
def __init__(self):
# reference to the head of the list
self.head = None
def add_to_head(self, value):
node = Node(value)
if self.head is not None:
node.set_next(self.head)
self.head = node
def contains(self, value):
if not self.head:
return False
# get a reference to the node we're currently at; update this as we traverse the list
current = self.head
# check to see if we're at a valid node
while current:
# return True if the current value we're looking at matches our target value
if current.get_value() == value:
return True
# update our current node to the current node's next node
current = current.get_next()
# if we've gotten here, then the target node isn't in our list
return False
def reverse_list(self):
prev = None
current = self.head
while current is not None:
next = current.next_node
current.next_node = prev
prev = current
current = next
self.head = prev