92.Reverse_Linked_List_II

25 年 6 月 27 日 星期五
119 字
1 分钟

problem

leetcode
python
# 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]:
        dummy = ListNode(next=head)
        p0 = dummy
        for _ in range(left-1):
            p0 = p0.next
        pre = None
        cur = p0.next
        for _ in range(right-left+1):
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp

        p0.next.next = cur
        p0.next = pre
        return dummy.next

https://leetcode.cn/problems/reverse-linked-list-ii/solutions/1992226/you-xie-cuo-liao-yi-ge-shi-pin-jiang-tou-teqq

Keep notice the position of cur and pre when the ending.

Insert a dummy node before head is because if left == 1, then we need a node before left. To record the address of head. So that is the function of dummy node.

文章标题:92.Reverse_Linked_List_II

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/92reverse_linked_list_ii[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。