反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* 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) {
m--;n--;
ListNode M = head;
ListNode N = head;
for(int i = 0; i < n-m; i++) {
N = N.next;
}
for(int i = 0; i < m; i++) {
M = M.next;
N = N.next;
}
List<Integer> listNodes = new ArrayList<>();
ListNode M1 = M;
while (M != N) {
listNodes.add(M.val);
M = M.next;
}
listNodes.add(N.val);
int len_listNodes = listNodes.size();
for(int i = 0; i < len_listNodes/2; i++) {
Integer temp = listNodes.get(i);
listNodes.set(i, listNodes.get(len_listNodes-1-i));
listNodes.set(len_listNodes-1-i, temp);
}
int i = 0;
while (M1 != N) {
M1.val = listNodes.get(i++);
M1 = M1.next;
}
N.val = listNodes.get(len_listNodes-1);
return head;
}
}
查看大佬的代码,他们将一个节点看作一个栈的结构,充分利用了栈的思想
// others
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null) {
return null;
}
int cnt = 1;
ListNode pre = null;
ListNode cur;
ListNode tail;
if (m == 1) { // 从头节点开始
cur = head;
tail = head;
while (cnt <= n && cur != null) {
ListNode next = cur.next;
cur.next = pre; // 将头节点弹出来
pre = cur; // 将弹出的头节点压入cur中
cur = next; // 重新将cur恢复
cnt++;
}
tail.next = cur;
return pre;
} else {
ListNode cutNode = head;
while (cnt < m - 1) {
cutNode = cutNode.next;
cnt++;
}
cur = cutNode.next;
tail = cutNode.next;
while (cnt < n && cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
cnt++;
}
cutNode.next = pre;
tail.next = cur;
return head;
}
}