Reverse linked list two

Given a one-way list, reverse the list from the m-N position

Idea 1: Break the linked list into two parts.

Find the starting point of the inversion, make a new list, and then connect the inversion to the old list.

Idea 1: code implementation

var reverseBetween = function(head, left, right) {
  if(! head)return null;
  let ret = new ListNode(-1,head); // Create a new list, the next node is head,
  let pre = ret;
  let cnt = right - left + 1; // The number of lists to be reversed
  while (--left) {
    pre =; // Find the starting node of the position to be reversed.
  } = reverse(, cnt); // Reverse the linked list
  return; // return the list. The next digit is the original list starting from head. The first digit is the virtual head
var reverse = function(head,n){ // Receive a linked list and the number to be reversed
  let pre = null;
  let cur = head;
  while (n--) {
    [, pre, cur] = [pre, cur,]; // Reverse linked list 1, pointer swap position method, swap node position
  } = cur; // join lists
  return pre; // Return the entire list reversed
Copy the code