给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
题目信息:递归或迭代
迭代,首先想到新建链表用头插法
然后发现遍历时改变指针指向更为方便
递归,也是改变指针指向,只是使用函数改变两个节点,然后递归直到改变整个列表
/**
* Definition for singly-linked list.
* 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)
* }
* }
*/
function reverseList(head: ListNode | null): ListNode | null {
let pre = null
let cur = head
let t = null
while (cur) {
t = cur.next
cur.next = pre
pre = cur
cur = t
}
return pre
}
/**
* Definition for singly-linked list.
* 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)
* }
* }
*/
function reverseList(head: ListNode | null): ListNode | null {
return reverse(null, head)
}
function reverse(pre: ListNode | null, cur: ListNode | null) {
if (!cur) return pre
const t = cur.next
cur.next = pre
return reverse(cur, t)
}