92. Reverse Linked List II

Leetcode

https://leetcode.com/problems/reverse-linked-list-ii/arrow-up-right

題目

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.

Example 1:

Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]

Example 2:

Input: head = [5], left = 1, right = 1
Output: [5]

解答

  • 方法一

把整個 linked list 分成三部分進行處理,[正常排序] - [逆排序] - [正常排序]

For example:

head = [1, 2, 3, 4, 5],left = 2,right = 4

最終答案是 1 -> 4 -> 3 -> 2 -> 5 ,我們主要要做的就是把中間的 2, 3, 4 逆排序過來

Runtime: 68 ms, faster than 89.41% of JavaScript online submissions for Reverse Linked List II.

Memory Usage: 38.9 MB, less than 78.24% of JavaScript online submissions for Reverse Linked List II.

測資

Last updated