LeetCode Daily Question 24
May 7th 2022
5 月 7 日 每日一题
题目:284. Peeking Iterator
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.
1 | Example 1: |
思路
I. Dummy Node
用于避免 reverse 的 left 为 head 的 edge case,结束时返回 dummy node 的 next 即可。
II. 移动指针,将指针指向 left,并且需要记录 left 的前一个 node,以便结束时 connect。需要注意的是循环的运行次数应该为 left - 1.
III. 对要求区域进行 reverse,需要记录 curr,prev 和 forwarding,流程为,首先记录 current node 的 next,然后将 current node 的 next 指向 prev,然后将 prev 更新为 current node,current node 更新为 forwarding node。reverse 的次数为 right - left + 1,这是因为第一次循环 prev 为 nullptr。
IV. 连接 reverse 区域与其余区域,此时 current 指向 node after right,并且 leftPrev 的 next 为 reverse 前的 left。首先将 reverse 前的 left 的 next 指向 current。然后将 leftPrev 的 next 指向 prev(right)。
代码
1 | class Solution { |