-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.py
More file actions
115 lines (83 loc) · 2.82 KB
/
Copy pathlinked_list.py
File metadata and controls
115 lines (83 loc) · 2.82 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
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, value):
new_node = Node(value)
new_node.next = self.head
self.head = new_node
def __str__(self):
result = []
current = self.head
string_representation = ""
while current:
string_representation += f"{{ {current.value} }} -> "
current = current.next
string_representation += "NULL"
return string_representation
def includes(self, value):
current = self.head
while current:
if current.value == value:
return True
current = current.next
return False
def append(self, value):
new_node = Node(value)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
def insert_before(self, value, new_value):
new_node = Node(new_value)
if not self.head:
raise TargetError("Cannot insert before in an empty list")
if self.head.value == value:
new_node.next = self.head
self.head = new_node
return
current = self.head
while current.next and current.next.value != value:
current = current.next
if current.next is None:
raise TargetError("Value not found in the list")
new_node = Node(new_value)
new_node.next = current.next
current.next = new_node
def insert_after(self, value, new_value):
if not self.head:
raise TargetError("Cannot insert after in an empty list")
current = self.head
while current and current.value != value:
current = current.next
if current is None:
raise TargetError("Value not found in the list")
new_node = Node(new_value)
new_node.next = current.next
current.next = new_node
def kth_from_end(self, k):
if k < 0:
raise TargetError("Negative value for k is not allowed")
current = self.head
runner = self.head
# Move runner k steps ahead
for _ in range(k):
if runner is None:
raise TargetError("k is out of range")
runner = runner.next
# Additional check if k is exactly the length of the list
if runner is None:
raise TargetError("k is out of range")
# Move both pointers until runner reaches the end
while runner.next:
current = current.next
runner = runner.next
return current.value
class TargetError(Exception):
pass