-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.py
More file actions
124 lines (90 loc) · 2.97 KB
/
linked_list.py
File metadata and controls
124 lines (90 loc) · 2.97 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
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
from typing import Generic, TypeVar
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, value: T) -> None:
self.value: T = value
self.prev: Node[T] = None
self.next: Node[T] = None
class DoublyLinkedList(Generic[T]):
length: int
head: Node[T] | None
tail: Node[T] | None
def __init__(self) -> None:
self.length = 0
self.head = None
self.tail = None
def prepend(self, item: T) -> None:
new_node = Node(item)
self.length += 1
if self.head is None:
self.head = self.tail = new_node
return
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
def insert_at(self, item: T, index: int) -> None:
if index == self.length:
self.append(item)
return
elif index == 0:
self.prepend(item)
return
current = self._get_node_at(index)
self.length += 1
new_node = Node(item)
# Linking the new node
new_node.next = current
new_node.prev = current.prev
# Rearranging the links of adjacent nodes
current.prev.next = new_node
current.prev = new_node
def append(self, item: T) -> None:
new_node = Node(item)
self.length += 1
if self.tail is None:
self.tail = self.head = new_node
self.tail.next = new_node
new_node.prev = self.tail
self.tail = new_node
def remove(self, item: T) -> T | None:
current = self.head
for i in range(self.length):
if current.value == item:
break
current = current.next
if current is None:
return
self.length -= 1
if self.length == 0:
value = self.head.value
self.head = self.tail = None
return value
if current.prev is not None:
current.prev.next = current.next
if current.next is not None:
current.next.prev = current.prev
if current == self.head:
self.head = current.next
if current == self.tail:
self.tail = current.prev
current.next = current.prev = None
return current.value
def get(self, index: int) -> T:
return self._get_node_at(index).value
def remove_at(self, index: int) -> T:
node = self._get_node_at(index)
self.length -= 1
if node.prev:
node.prev.next = node.next
node.prev = None
if node.next:
node.next.prev = node.prev
node.next = None
return node.value
def _get_node_at(self, index: int) -> Node[T]:
if index < 0 or index >= self.length:
raise Exception('Out of bounds')
current = self.head
for i in range(index):
current = current.next
return current