链表

反转链表-代码随想录

  • 思路:

    • 咱们能够申请两个指针,第一个指针叫 pre,最后是指向 null 的。
    • 第二个指针 cur 指向 head,而后一直遍历 cur。
    • 每次迭代到 cur,都将 cur 的 next 指向 pre,而后 pre 和 cur 后退一位。
    • 都迭代完了(cur 变成 null 了),pre 就是最初一个节点了。
var reverseList = function (head) {  if (!head || !head.next) {    return head;  }  let pre = null,    cur = head,    temp = null;  while (cur) {    temp = cur.next;    cur.next = pre;    pre = cur;    cur = temp;  }  return pre;};