力扣刷题92. 反转链表 II(java)

题目

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

思路

  1. 同反转链表一 ,采用两个指针记录反转。
  2. 此题目需要记录反转条件,记录反转的m前n的后节点
  3. 特殊情况 全部反转
  4. 特殊情况 只反转一个节点
/**
 * 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(m==n) return head;
        ListNode prev = null;
        ListNode curr = head;
        ListNode nodeMPre = null;
        ListNode nodeM = null;
        ListNode nodeN = null;
        ListNode nodeNNext = null;
        int index = 1;
        while (curr != null) {
            if(index < m || index > n){
                prev = curr;
                curr = curr.next;
            }else if(index == m){
                nodeMPre = prev;
                nodeM = curr;
                prev = curr;
                curr = curr.next;
            }else if(index == n){
                nodeN = curr;
                nodeNNext = curr.next;
                ListNode nextTemp = curr.next;
                curr.next = prev;
                prev = curr;
                curr = nextTemp;
            }else {
                ListNode nextTemp = curr.next;
                curr.next = prev;
                prev = curr;
                curr = nextTemp;
            }
            index ++;
        }
        if(nodeMPre == null){
            head = nodeN;
        }else{
            nodeMPre.next = nodeN;
        }
        nodeM.next = nodeNNext;
        return head;
    }
}

你可能感兴趣的:(力扣刷题92. 反转链表 II(java))