LinkedList - 92. Reverse Linked List II

55
  1. Reverse Linked List II

Reverse a linked list from position m to n. Do it in one-pass.

**Note: **1 ≤ mn ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

思路:

找到m的前一位,然后翻转n-m+1个节点,链表翻转类型的题目常规套路都是使用一个dummy来保存head链表头。因为题目说了链表长度比m和n都要大,所以不用额外关注m和n会不会导致空指针。

代码:

java:

/**

 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
       // if (head == null) return head;
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode prev = dummy;
        for (int i = 0; i < m - 1; i++) prev = prev.next;
        
        // reverse list
        ListNode curr = prev.next;
        ListNode next = curr.next;
        
        for (int i = 0; i < n - m; i++) {
            curr.next = next.next;
            next.next = prev.next;
            prev.next = next;
            
            next = curr.next; 
        }
        
        return dummy.next;
    }
}