反转范围之前有节点,prev就指向该节点,没有就prev=null;
一、头插法
class Solution {public ListNode reverseList(ListNode head) {ListNode header = new ListNode(-1);ListNode cur = head;while(cur != null) {ListNode tmp = cur.next;cur.next = header.next;header.next = cur;cur = tmp;}return header.next;}
}
class Solution {public ListNode reverseBetween(ListNode head, int left, int right) {// 头插法ListNode dummy = new ListNode(0);dummy.next = head;ListNode prev = dummy; // 要反转的序列前一个节点for (int i = 0; i < left - 1; i++) {prev = prev.next;}ListNode cur = prev.next; // 当前真正要反转的节点for (int i = 0; i < right - left; i++){ // 反转r-l次ListNode tmp = cur.next;cur.next = tmp.next;tmp.next = prev.next;prev.next = tmp;}return dummy.next;}
}