Skip to content

链表反转

链表反转

示例

输入:head = [1,2,3]

输出:[3,2,1]

代码

javascript
export function ListNodeJs(val, next) {
  this.val = (val === undefined ? 0 : val)
  this.next = (next === undefined ? null : next)
}
typescript
export class ListNode {
  val: number
  next: ListNode | null
  constructor(val?: number, next?: ListNode | null) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
  }
}
javascript
// 输入:[1, 2, 3]
// 输出:[3, 2, 1]

import { ListNodeJs } from '../../utilsJs'

export function listNodeReverse (head) {
  if (!head) {
    return head
  }
  let res = new ListNodeJs(head.val)
  let middle = res
  while (head.next) {
    head = head?.next
    res = new ListNodeJs(head.val)
    res.next = middle
    middle = res
  }
  return res
}
typescript
// 输入:[1, 2, 3]
// 输出:[3, 2, 1]

import { ListNode } from "../../utils"

export function listNodeReverse (head: ListNode | null): ListNode | null {
  if (!head) {
    return head
  }
  let res: ListNode | null = new ListNode(head.val)
  let middle = res
  while (head.next) {
    head = head?.next
    res = new ListNode(head.val)
    res.next = middle
    middle = res
  }
  return res
}