Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Example1:
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
Example2:
Input: head = [5], left = 1, right = 1
Output: [5]
这道题思考很简单,就是找到最开始需要反转的前一个点和第一个点记下来, 然后反转,再把反转的最后一个点以及反转后面的第一个点记下来,最后串联起来。需要注意边界,比如第一个点就是需要反转的点,所以设置一个dummy node会让整个过程简化。
/**
* 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 || left >= right || head.next == null) {
return head;
}
//寻找需要反转的第一个点以及之前的点。之前的点用ps记住,第一个点用start记住。注意start不要指向head,要指向ps.next
ListNode dummy = new ListNode(0, head);
ListNode ps = dummy;
int step = right - left + 1;
while (--left > 0) {
ps = ps.next;
head = head.next;
}
ListNode start = ps.next;
ListNode prev = ps;
ListNode next = null;
//反转需要反转的list,之后prev记住的是反转的最后一个点,head是反转后的第一个点
while (step-- > 0 && head != null) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
//把该串联的三块串联号
ps.next = prev;
start.next = head;
return dummy.next;
}
}