Skip to content
On this page

常规解法

将每次遍历的节点放在前面 这样可以做到逆序

typescript
function reverseList2(head: ListNode | null): ListNode | null {
  //返回值
  let res = new ListNode();
  while (head) {
    let temp = new ListNode();
    res.val = head.val;
    //临时节点的下一个节点是当前节点
    temp.next = res;
    //返回值变为空->下一个节点是当前节点
    res = temp;
    head = head.next;
  }
  //返回下一个节点 因为当前节点为空
  return res.next;
}

通过保存到动态数组中 反转在重新创建链表

typescript
function reverseList(head: ListNode | null): ListNode | null {
  let arr: Array<number> = [];
  //把数据保存到数组里
  while (head) {
    arr.push(head.val);
    //前进一步
    head = head.next;
  }
  if (!arr.length) {
    return null;
  }
  arr = arr.reverse();

  //指针
  let temp = new ListNode();
  //保存指针
  let cur = temp;
  arr.forEach((v, i, arr) => {
    temp.val = v;
    if (i != arr.length - 1) {
      temp.next = new ListNode();
      temp = temp.next;
    }
  });

  return cur;
}

11.6 复习手写

typescript
function reverseList(head: ListNode | null): ListNode | null {
  let cur = new ListNode();
  while (head) {
    cur.val = head.val;
    let temp = new ListNode(0, cur);
    cur = temp;
    head = head.next;
  }
  return cur.next;
}