Skip to content

链表刷题模板

链表相关的题目,关键往往是需要创建一个*「空的根节点」「指针」*,再通过 while 循环让指针不停地移到下一位来进行遍历。

因为有根节点的存在,我们不需要考虑边界条件,比如 head 是否为空。

js
function travesal(head) {
  const root = new ListNode(0, head)
  const cur = root
  while (cur.next) {
    // 这里的cur.next就是当前正在访问的节点
    // 执行一些操作...

    // 指向下一个子节点
    cur = cur.next
  }
  // 返回头部
  return root.next
}
function travesal(head) {
  const root = new ListNode(0, head)
  const cur = root
  while (cur.next) {
    // 这里的cur.next就是当前正在访问的节点
    // 执行一些操作...

    // 指向下一个子节点
    cur = cur.next
  }
  // 返回头部
  return root.next
}