ZhangZhihui's Blog  

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.

 

Example 1:

Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]

Example 2:

Input: head = [5], left = 1, right = 1
Output: [5]

 

Constraints:

  • The number of nodes in the list is n.
  • 1 <= n <= 500
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= n

 

My Solution:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseBetween(self, head, left, right):
        """
        :type head: Optional[ListNode]
        :type left: int
        :type right: int
        :rtype: Optional[ListNode]
        """

        if left == right or head.next is None:
            return head

        left_node = None
        right_node = None
        a_list = []
        node = head
        i = 1
        while i <= right:
            if i == left:
                left_node = node
            if i == right:
                right_node = node
            
            if i >= left:
                a_list.append(node.val)

            if node.next:
                node = node.next
            i += 1

        node = left_node
        for i in range (left, right + 1):
            node.val = a_list.pop()
            node = node.next
        
        return head

 

 

ChatGPT's Solution:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseBetween(self, head, left, right):
        """
        :type head: Optional[ListNode]
        :type left: int
        :type right: int
        :rtype: Optional[ListNode]
        """

        if left == right or head.next is None:
            return head

        dummy = ListNode()
        dummy.next = head
        prev = dummy

        # Move prev to one node before the left-th node
        for _ in range(left - 1):
            prev = prev.next
        
        # Reverse the sublist from left to right
        curr = prev.next
        next_node = None
        for _ in range(right - left):
            next_node = curr.next
            curr.next = next_node.next
            next_node.next = prev.next
            prev.next = next_node
        
        return dummy.next

 

 

posted on 2025-03-23 08:10  ZhangZhihuiAAA  阅读(9)  评论(0)    收藏  举报