Reverse Linked List

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

 

 

class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        
        dummy = ListNode(None)
        dummy.next = head

        pre = dummy
        for i in range(left - 1):
            pre = pre.next

        head2 = pre
        pre = head2.next
        cur = pre.next
        for i in range(right - left):
            pre.next = cur.next 
            cur.next = head2.next
            head2.next = cur    # 头插法
            cur = pre.next
        
        return dummy.next
View Code

 

posted @ 2022-11-11 23:18  7aughing  阅读(13)  评论(0编辑  收藏  举报