题目

给定一个链表,反转链表

思路

             1      -> 2       -> 8 -> 9 -> 0 -> 5 -> null
null(pre)    1(cur) -> 2(next) -> 8 -> 9 -> 0 -> 5 
null(pre) <- 1(cur)    2(next) -> 8 -> 9 -> 0 -> 5 
null      <- 1(pre)    2(cur)  -> 8 -> 9 -> 0 -> 5
...
null <- 1 <- 2 <- 8 <- 9 <- 0 <- 5(pre) null(cur) 

代码

//反转单向列表
//   1 -> 2 -> 8 -> 9 -> 0 -> 5
//A: null(pre)    1(cur) -> 2(next) -> 8 -> 9 -> 0 -> 5
//B: null(pre) <- 1(cur)    2(next) -> 8 -> 9 -> 0 -> 5
//C: null      <- 1(pre)    2(cur) -> 8 -> 9 -> 0 -> 5
function reverseList(list) {
  let pre = next = null, cur = list
  while(cur) {
    next = cur.next   //A
    cur.next = pre    //B
    pre = cur         //C
    cur = next        //C
  }
  return pre
}

class Node {
  constructor(val) {
    this.val = val
    this.next = null
  }
}

function createList(values) {
  if (values.length === 0) return null
  let head = new Node(values[0]), p = head
  for (let i = 1; i < values.length; i++) {
    p.next = new Node(values[i])
    p = p.next
  }
  return head
}

function showList(list) {
  let p = list
  let arr = []
  while (p) {
    arr.push(p.val)
    p = p.next
  }
  console.log(arr.join('->'))
}

let list = createList([1,2,8,9,0,5])
showList(list)
let list2 = reverseList(list)
showList(list2)