Skip to content

Commit 2c8b4c1

Browse files
committed
reafactor(data structure, linked list): add negative values validation
1 parent 85adea4 commit 2c8b4c1

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

datastructures/linked_lists/singly_linked_list/single_linked_list.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,9 @@ def reverse_between(self, left: int, right: int) -> Optional[SingleNode]:
394394
if left > right:
395395
raise ValueError(f"left {left} cannot be greater than right {right}")
396396

397+
if left < 1 or right < 1:
398+
raise ValueError("left and right must be positive integers")
399+
397400
if self.head is None or self.head.next is None:
398401
return self.head
399402

@@ -402,6 +405,9 @@ def reverse_between(self, left: int, right: int) -> Optional[SingleNode]:
402405
f"right {right} cannot be greater than the length of the linked list {len(self)}"
403406
)
404407

408+
if left == right:
409+
return self.head
410+
405411
# Move the 2 pointers until they reach the proper starting point in the list
406412
current_pointer, previous_pointer = self.head, None
407413

@@ -463,6 +469,9 @@ def reverse_between_with_dummy(self, left: int, right: int) -> Optional[SingleNo
463469
if left > right:
464470
raise ValueError(f"left {left} cannot be greater than right {right}")
465471

472+
if left < 1 or right < 1:
473+
raise ValueError("left and right must be positive integers")
474+
466475
if self.head is None or self.head.next is None:
467476
return self.head
468477

@@ -492,10 +501,9 @@ def reverse_between_with_dummy(self, left: int, right: int) -> Optional[SingleNo
492501
return dummy.next
493502

494503
def unshift(self, node_: SingleNode) -> SingleNode:
495-
if self.head:
496-
return node_
497504
node_.next = self.head
498-
return node_
505+
self.head = node_
506+
return self.head
499507

500508
def insert(self, node_, pos):
501509
counter = 1
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from typing import Tuple
2+
import sys
3+
24

35
# Type alias for the best word info: (length, original_index)
46
WordInfo = Tuple[int, int]
57
# Initialize with a very large length to ensure the first word always wins
6-
INF_WORD_INFO: WordInfo = (float("inf"), float("inf"))
8+
INF_WORD_INFO: WordInfo = (sys.maxsize, sys.maxsize)

0 commit comments

Comments
 (0)