题解 | #链表内指定区间反转#

链表内指定区间反转

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

from os import removexattr

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @param m int整型
# @param n int整型
# @return ListNode类
#
class Solution:
    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
        # write code here
        prehead = ListNode(-1)
        prehead.next = head

        count = 1
        pre = prehead
        curr = head

        while count < m:
            pre = curr
            curr = curr.next
            count += 1

        # 已经找到m,开始反转,count=m

        while count < n:
            temp = curr.next
            curr.next = temp.next
            temp.next = pre.next
            pre.next = temp
            # 更新pre,curr
            # pre = curr
            # curr = temp
            count += 1
            # print(count)

        return prehead.next

#我的实习求职记录#
实习算法题题解 文章被收录于专栏

实习算法题

全部评论
加入头结点的原因,这样头结点肯定不会被反转,修改更容易,否则要考虑m是否等于1
点赞 回复 分享
发布于 2023-12-07 11:15 北京

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务