https://leetcode.com/problems/reverse-linked-list-ii/
92. Reverse Linked List II
- Total Accepted: 85657
- Total Submissions: 293208
- Difficulty: Medium
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Code
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ dummy = ListNode(3) dummy.next = head prev_t = dummy for i in xrange(m-1): prev_t = prev_t.next rev_h = rev_t = prev_t.next new_h = rev_h.next for i in xrange(m, n): new_h_next = new_h.next new_h.next = rev_h rev_h = new_h new_h = new_h_next prev_t.next = rev_h rev_t.next = new_h return dummy.next
Idea
I saw discussions on Leetcode that many people use several pointers as I do. So I believe my (iterative) solution is not too bad. Let me use a picture to illustrate prev_t
, `rev_h`, `rev_t`, `new_h`: