题解 | #重建二叉树#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
本来的思路是——关注节点关系的变化,构思是 p1->p3, p2->p1, p3->p2......, 所以写出了下面的代码:
function ReverseList(pHead) {
  if (!pHead) {
    return null;
  }
  let curNode = pHead;
  let next = pHead.next;
  while (next) {
    pHead.next = next.next;
    next.next = curNode;
    curNode = next;
    next = pHead.next;
  }
  return curNode;
}
殊不知节点关系已经存在两个声明的变量里了,三节点法是利用率更高的
function ReverseList(pHead) {
    // write code here
    let pre = null;
    let next = null;
    while(pHead !== null) {
        next = pHead.next;
        pHead.next = pre;
        pre = pHead;
        pHead = next;
    }
    return pre;
}
查看7道真题和解析


