파비의 매일매일 공부기록

2023.09.07 Today's Challenge 본문

Problem Solving/LeetCode

2023.09.07 Today's Challenge

fabichoi 2023. 9. 7. 23:45

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

 

Reverse Linked List II - LeetCode

Can you solve this real interview question? Reverse Linked List II - 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 lis

leetcode.com

링크드리스트 문제

class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        if not head or left == right:
            return head

        dummy = ListNode(0, head)
        prev = dummy

        for _ in range(left - 1):
            prev = prev.next

        current = prev.next

        for _ in range(right - left):
            next_node = current.next
            current.next, next_node.next, prev.next = next_node.next, prev.next, next_node
        
        return dummy.next
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.09.09 Today's Challenge  (0) 2023.09.09
2023.09.08 Today's Challenge  (0) 2023.09.08
2023.09.06 Today's Challenge  (0) 2023.09.06
2023.09.05 Today's Challenge  (0) 2023.09.05
2023.09.04 Today's Challenge  (0) 2023.09.04
Comments