給你單鏈表的頭指針 head 和兩個整數 left 和 right ,其中 left <= right 。請你反轉從位置 left 到位置 right 的鏈表節點,返回 反轉後的鏈表 。
示例 1:
輸入:head = [1,2,3,4,5], left = 2, right = 4
輸出:[1,4,3,2,5]
示例 2:
輸入:head = [5], left = 1, right = 1
輸出:[5]
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if (head == null || head.next == null || left == right) {
return head;
}
//虛擬節點爲了避免頭節點爲空
ListNode dummy = new ListNode(-1);
dummy.next = head;
//分別記錄要反轉的前節點和要反轉的第一個節點
ListNode currDummy = dummy;
ListNode prevDummy = null;
ListNode prev = null;
ListNode curr = null;
for (int i = 0; i < left; i++) {
prevDummy = currDummy;
currDummy = currDummy.next;
}
curr = currDummy;
//反轉範圍內的節點
for (int i = left; i <= right && curr !=null; i++){
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
//拼接節點,反轉前的結點 拼反轉後的頭結點
prevDummy.next = prev;
//反轉後的最後一個節點拼接right後的那個節點
currDummy.next = curr;
return dummy.next;
}
}
//leetcode submit region end(Prohibit modification and deletion)