标签: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.
标签:paper public move mes its turn pos one tps
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9450908.html