[Java] Leetcode 92. Reverse Linked List II [LinkedList Reversal #2]

แชร์
ฝัง
  • เผยแพร่เมื่อ 12 ก.ย. 2024

ความคิดเห็น • 4

  • @rajaditya4689
    @rajaditya4689 2 ปีที่แล้ว +2

    the code gives Wrong Answer, while submission on Leetcode for the Input --> List Node = [3, 4] left = 1, right = 2

  • @rajaditya4689
    @rajaditya4689 2 ปีที่แล้ว

    Could you code in the first method? cause this became confusing in the end.

  • @leonlow9911
    @leonlow9911 ปีที่แล้ว

    Solution for first method:
    class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
    # base case
    if head is None: return None
    # define current and count
    current = head
    prevLeftNode = None
    afterRightNode = None
    leftNode = None
    count = 1
    # iterate through linked list
    while current is not None:
    if count == left - 1:
    prevLeftNode = current
    if count == left:
    leftNode = current
    if count == right + 1:
    afterRightNode = current
    count += 1
    current = current.next
    reversedLL = self.reverse(leftNode, afterRightNode)
    if prevLeftNode:
    prevLeftNode.next = reversedLL
    else:
    head = reversedLL
    if afterRightNode:
    leftNode.next = afterRightNode
    if not prevLeftNode and not afterRightNode:
    return reversedLL
    return head
    def reverse(self, left, right):
    # define prev and current
    current = left
    prev = None
    # iterate through linked list
    while current != right:
    temp = current.next
    current.next = prev
    prev = current
    current = temp
    return prev