92. Reverse Linked List II
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
/** * 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) { ListNode newhead = new ListNode(-1); newhead.next = head; if(head==null||head.next==null) return newhead.next; ListNode startpoint = newhead;//startpoint指向需要开始reverse的前一个 ListNode node1 = null;//需要reverse到后面去的节点 ListNode node2 = null;//需要reverse到前面去的节点 for (int i = 0; i < n; i++) { if (i < m-1){ startpoint = startpoint.next;//找真正的startpoint } else if (i == m-1) {//开始第一轮 node1 = startpoint.next; node2 = node1.next; }else { node1.next = node2.next;//node1交换到node2的后面 node2.next = startpoint.next;//node2交换到最开始 startpoint.next = node2;//node2作为新的点 node2 = node1.next;//node2回归到node1的下一个,继续遍历 } } return newhead.next; } }
https://www.cnblogs.com/springfor/p/3864303.html
class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if(head == null) return null; ListNode dummy = new ListNode(-1); ListNode pre = dummy; dummy.next = head; for(int i = 0; i < m - 1; i++) { pre = pre.next; } ListNode cur = pre.next; for(int i = 0; i < n-m; i++) { ListNode move = cur.next; cur.next = move.next; move.next = pre.next; pre.next = move; } return dummy.next; } }
和25保持一致的写法,少记点幺蛾子屮