演算法-連結串列內指定區間反轉
阿新 • • 發佈:2020-12-10
技術標籤:演算法
連結串列反轉
輸入一個連結串列,反轉連結串列後,輸出新連結串列的表頭。
例如:輸入{1, 2, 3},返回{3, 2, 1}。
public static ListNode reverse (ListNode head) { ListNode pre = null, temp = new ListNode(0); while (head != null) { temp = new ListNode(head.val); temp.next = pre; pre = temp; head = head.next; } return temp; }
題目描述
將一個連結串列 m 位置到 n 位置之間的區間反轉,要求時間複雜度O(n) ,空間複雜度O(1) 。
例如:
給出的連結串列為 1 → 2 → 3 → 4 → 5 → NULL,1→2→3→4→5→NULL,m=2,n=4,
返回 1 → 4 → 3 → 2 → 5 → NULL。
注意:
給出的 滿足以下條件:1 ≤ m ≤ n ≤ 連結串列長度。
//連結串列內指定區間反轉
public ListNode reverseBetween (ListNode head, int m, int n) {
ListNode node = head;
ListNode pre = null;
ListNode last = new ListNode(0);
ListNode temp = new ListNode(0);
ListNode tempFirst = new ListNode(0);
ListNode currFirst = tempFirst;
ListNode currLast = new ListNode(0);
int count = 0;
while (node != null) {
++count;
if (count <= (m - 1)) {
ListNode tmp = new ListNode(node.val);
currFirst. next = tmp;
currFirst = tmp;
}
if (count >= m && count <= n) {
temp = new ListNode(node.val);
if (count == m) {
currLast = temp;
}
temp.next = pre;
pre = temp;
if (count == n) {
last = node.next;
break;
}
}
node = node.next;
}
currFirst.next = temp;
currLast.next = last;
return tempFirst.next;
}