题目

迭代

var reverseList = function(head) {
  let list = head;
  let result = null;
  while(list){
    const next = list.next;
    list.next = result;
    result = list;
    list = next;
  }
  return result;
};

递归,这个方法我看了半天。写出这个方法要知道一点,在js中函数传参,如果参数是对象,则传递的是地址值,如果在函数中改变对象中的属性,那么函数外面对应的对象值也会变。例:

function test(obj){
  obj.a = 2;
}
let obj = {
  a: 1
}
test(obj);
console.log(obj);//{ a: 2 }

答案:

var reverseList = function(head) {
  if(head===null||head.next===null)return head;
  const temp = reverseList(head.next);
  head.next.next = head;
  head.next = null;
  return temp;
};