0092-leetcode算法实现之反转链表II-reverseLinkedListII-python&golang实现
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
提示:
链表中节点数目为 n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
进阶: 你可以使用一趟扫描完成反转吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
python
# 0092.反转链表II
# https://leetcode-cn.com/problems/reverse-linked-list-ii/solution/java-shuang-zhi-zhen-tou-cha-fa-by-mu-yi-cheng-zho/
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def reverseLinkedListII(self, head: ListNode, left: int, right: int) -> ListNode:
"""
双指针, 头插法
:param head:
:param left:
:param right:
:return:
"""
dummyHead = ListNode(0)
dummyHead.next = head
# 初始化
guard = dummyHead
p = dummyHead.next
# 指针移动相应位置
for i in range(0, left-1):
guard = guard.next
p = p.next
#
for i in range(0, right-left):
removed = p.next
p.next = p.next.next
removed.next = guard.next
guard.next = removed
retNode = dummyHead.next
dummyHead.next = None
return retNode
golang
// 双指针
func reverseLinkedListII(head *ListNode, left, right int) *ListNode {
dummyHead := &ListNode{}
dummyHead.Next = head
guard := dummyHead
p := dummyHead.Next
for i := 0; i < left-1; i++ {
guard = guard.Next
p = p.Next
}
for i := 0; i < right-left; i++ {
removed := p.Next
p.Next = p.Next.Next
removed.Next = guard.Next
guard.Next = removed
}
return dummyHead.Next
}