-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathreverse.py
More file actions
51 lines (38 loc) · 1.14 KB
/
reverse.py
File metadata and controls
51 lines (38 loc) · 1.14 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
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
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):
self.next_node = new_next
class LinkedList:
def __init__(self):
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
current = self.head
while current:
if current.get_value() == value:
return True
current = current.get_next()
return False
def reverse_list(self, node, prev):
if self.head is None or self.head.next_node is None:
return
prev = None
current = self.head
while current:
next_element = current.next_node
current.next_node = prev
prev = current
current = next_element
self.head = prev