본문 바로가기

Algorithm/파이썬 알고리즘 인터뷰 스터디

[연결리스트] 19 역순 연결 리스트 II(Reverse Linked List II)

<LeetCode 문제>

https://leetcode.com/problems/reverse-linked-list-ii/

 

Reverse Linked List II - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

인덱스 m에서 n까지를 역순으로 만드는 문제입니다. 이때, 인덱스는 0이 아닌 1부터 시작합니다.

<풀이>

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
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

<학습내용>

1.

<학습이 필요한 내용>

1.