92. Reverse Linked List II

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了92. Reverse Linked List II相关的知识,希望对你有一定的参考价值。

92. Reverse Linked List II

https://www.youtube.com/watch?v=esl_A_pzBcg&t=304s

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
      if(head == null || head.next == null){
        return head;
      }
      
      ListNode dummy = new ListNode(0);
      dummy.next = head;
      ListNode prevm = dummy;
      ListNode nodem = head;
      ListNode noden = head;
      
      for(int i = 0; i < m - 1; i++){
        prevm = nodem;
        nodem = nodem.next;
      }
      
      for(int i = 0; i < n - 1; i++){
        noden = noden.next;
      }
      
      while( nodem != noden){
        prevm.next = nodem.next;
        nodem.next = noden.next;
        noden.next = nodem;
        nodem = prevm.next;
      }
      return dummy.next;
    
    }
}


// first, we need to find the position for m and n nodes, 
// since in the steps we are doing later, we use a prevm( the node before m) to refer m node. 
// so we also need a node prev m, to have a initaized position before m. (prev m never changes)

// second step, we move node m after node n, and update node m as the prevm.next. do this n-m times 
// until node m is the same as node n. 

// i know there are lots of messy steps involved in doing the pointer changes, but think this way 
// all you have to do is move the node m after node n, and update node m as the one after prev, 
// its easier to think about it without thinking about linked list first, draw this on the paper
// and once this process makes sense to you, you can pay attenton to the linked list connection part, which is easy tp 
// think about it on its own, and each " move node m after node n"  is the same step. 

 

以上是关于92. Reverse Linked List II的主要内容,如果未能解决你的问题,请参考以下文章

92. Reverse Linked List II

92. Reverse Linked List II

92. Reverse Linked List II

#Leetcode# 92. Reverse Linked List II

LeetCode 92. Reverse Linked List II

92. Reverse Linked List IIMedium