Scribbling

LeetCode: 92. Reverse Linked List II 본문

Computer Science/Coding Test

LeetCode: 92. Reverse Linked List II

focalpoint 2021. 10. 12. 22:41
# 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]:
        new_head = ListNode(val=0, next=head)
        count = 0
        ptr = new_head
        
        prev, cur = None, new_head
        nxt = head
        for i in range(left):
            prev = cur
            cur = nxt
            nxt = cur.next
        
        cut_tail = prev
        reversed_head = cur
        
        for i in range(right-left):
            prev = cur
            cur = nxt
            nxt = cur.next
            cur.next = prev
            
        reversed_tail = cur
        cut_head = nxt

        cut_tail.next = reversed_tail
        reversed_head.next = cut_head
        
        return new_head.next