反轉從位置 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;
}
}