무냐의 개발일지
LL: Reverse Between 해설 본문
👩💻 문제
You are given a singly linked list and two integers start_index and end_index.
Your task is to write a method reverse_between within the LinkedList class that reverses the nodes of the linked list from start_index to end_index (inclusive using 0-based indexing) in one pass and in-place.
Note: the Linked List does not have a tail which will make the implementation easier.
Assumption: You can assume that start_index and end_index are not out of bounds.
Input
- The method reverse_between takes two integer inputs start_index and end_index.
- The method will only be passed valid indexes (you do not need to test whether the indexes are out of bounds)
Output
- The method should modify the linked list in-place by reversing the nodes from start_index to end_index.
- If the linked list is empty or has only one node, the method should return None.
💡 풀이
# WRITE REVERSE_BETWEEN METHOD HERE #
def reverse_between(self, start_index, end_index):
if self.length <= 1 :
return self
dummy = Node(0)
dummy.next = self.head #cautious
prev = dummy
for _ in range(start_index):
prev = prev.next
current = prev.next
for _ in range(end_index - start_index):
after = current.next
current.next = after.next
after.next = prev.next
prev.next = after
self.head = dummy.next
✍️ 해설
🥳 배운점
역시 ... 손으로 그려가면서 풀어야 되는 거여써
'LeetCode 코딩테스트' 카테고리의 다른 글
DLL: Swap Nodes in Pairs (Advanced!) (0) | 2024.06.18 |
---|---|
Stack : sort_stack 해설 (0) | 2024.06.17 |
627. Swap Salary (0) | 2024.05.09 |
1791. Find Center of Star GraphS (0) | 2024.05.09 |
1920. Build Array from Permutation (0) | 2024.04.15 |