LeetCode_Reverse Linked List II

Reverse Linked List II

Reverse a linked list from position m to n. Do it in one-pass.
(旋转link_list[m:n+1])

Note: 1 ≤ m ≤ n ≤ length of list.

Example:



1. In-place

具体实现方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
new_head = ListNode(0)
new_head.next = head

p_pre = new_head
p_cur = head
for i in range(1, m):
p_pre = p_pre.next
p_cur = p_cur.next

for j in range(n-m):
p_head = p_pre.next
p_pre.next = p_cur.next
p_temp = p_cur.next
p_cur.next = p_cur.next.next
p_temp.next = p_head

return new_head.next