92. Reverse Linked List II
Reverse a linked list from position _m_ to _n_. Do it in one-pass.
Note: 1 ≤ _m_ ≤ _n_ ≤ length of list.
Example:
1 2
| Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
|
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution(object): def reverseBetween(self, head, m, n): dummy = ListNode(0) dummy.next = head
cur, prev = head, dummy for _ in range(m - 1): cur = cur.next prev = prev.next
for _ in range(n - m): temp = cur.next cur.next = temp.next temp.next = prev.next prev.next = temp
return dummy.next
|