-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinked_list.py
62 lines (47 loc) · 1.33 KB
/
linked_list.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
class LinkedList:
"""
Linked-List.
"""
class Element:
"""
Linked-List element.
"""
def __init__(self, value):
"""
Generates a linked-list element with
the given value.
"""
self.value = value
self.prev = None
self.next = None
def __init__(self):
"""
Generates an empty linked-list.
"""
self.head = None
self.tail = None
def add(self, value):
"""
Inserts value into the linked-list.
"""
if self.tail == None:
self.head = self.tail = self.Element(value)
else:
self.tail.next = self.Element(value)
self.tail.next.prev = self.tail
self.tail = self.tail.next
def moveToFront(self, element):
"""
Moves element to the front of the linked-list.
"""
if element is self.head:
return
element.prev.next = element.next
if element is self.tail:
self.tail = element.prev
else:
element.next.prev = element.prev
self.head.prev = element
element.next = self.head
element.prev = None
self.head = element