[코테] 리트코드 연결 리스트 92. Reverse Linked List II
92. Reverse Linked List II
문제 링크
https://leetcode.com/problems/reverse-linked-list-ii/description/
문제 설명
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
제한 사항
- The number of nodes in the list is n.
- 1 <= n <= 500
- -500 <= Node.val <= 500
- 1 <= left <= right <= n
입출력 예 #1
- Input: head = [1,2,3,4,5], left = 2, right = 4
- Output: [1,4,3,2,5]
입출력 예 #2
- Input: head = [5], left = 1, right = 1
- Output: [5]
문제 풀이
반복 구조로 노드를 뒤집는데 start, end, tmp 세개의 노드로 구현한다.
아직까지 나 스스로 생각해서 문제를 풀 수는 없기에 열심히 해야지.
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
# 예외 처리
if not head or left == right:
return head
root = start = ListNode(None)
root.next = head
# start, end 지정
for _ in range(left - 1):
start = start.next
end = start.next
# 반복하면서 노드 차례대로 뒤집기
for _ in range(right - left) :
tmp, start.next, end.next = start.next, end.next, end.next.next
start.next.next = tmp
return root.next
Comments