反轉從位置 m 到 n 的鍊錶。請使用一趟掃瞄完成反轉。輸入:1->2->3->4->5->null, m = 2, n = 4輸出:1->4->3->2->5->null
維護乙個index變數來記錄下乙個節點是否是第m個節點
如果是第m個節點,那麼對下乙個節點採用頭插法重建鍊錶,直到第n個節點
剩餘節點連線到第m個節點後面
python
class solution:
def reversebetween(self, head: listnode, m: int, n: int) -> listnode:
if not head or not head.next:
return head
# 記錄
res, i = listnode(0), 0
res.next = head
tmp = res
while head and i < m - 1:
tmp, head, i = tmp.next, head.next, i + 1
#showlist(head)
# 反轉
last = head
while head and i < n:
tmp1, head = head, head.next
tmp.next, tmp1.next = tmp1, tmp.next
i += 1
#showlist(tmp)
#showlist(res)
# 連線
if last:
last.next = head
return res.next
leetcode 92反轉鍊錶
反轉從位置 m 到 n 的鍊錶。請使用一趟掃瞄完成反轉。說明 1 m n 鍊錶長度。示例 輸入 1 2 3 4 5 null,m 2,n 4 輸出 1 4 3 2 5 null definition for singly linked list.public class listnode class...
LeetCode 92 反轉鍊錶 II
反轉從位置 m 到 n 的鍊錶。請使用一趟掃瞄完成反轉。說明 1 m n 鍊錶長度。示例 輸入 1 2 3 4 5 null,m 2,n 4 輸出 1 4 3 2 5 null 5ms definition for singly linked list.public class listnode c...
leetcode92 反轉鍊錶 II
反轉從位置 m 到 n 的鍊錶。請使用一趟掃瞄完成反轉。說明 1 m n 鍊錶長度。示例 輸入 1 2 3 4 5 null,m 2,n 4輸出 1 4 3 2 5 null思路 先往後遍歷找到需要反轉的節點作為起點 count m 然後按照劍指offer 反轉鍊錶 的思路,設定curr,pre,p...