码迷,mamicode.com
首页 > 其他好文 > 详细

92. Reverse Linked List II

时间:2018-08-09 19:33:01      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:paper   public   move   mes   its   turn   pos   one   tps   

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

标签:paper   public   move   mes   its   turn   pos   one   tps   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9450908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!