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.
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
posted on 2018-08-09 18:22 猪猪🐷 阅读(97) 评论(0) 收藏 举报
浙公网安备 33010602011771号