一、迭代法
借助pre 变量与next 变量,防止迭代过程中丢失链表
type LinkedNode = {
num: number;
next: LinkedNode;
};
function reverse(head: LinkedNode) {
let pre: LinkedNode | null = null;
let next: LinkedNode | null = null;
while (head) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
二、递归法
借助函数保存指针变量,防止丢失链表
type LinkedNode = {
num: number;
next: LinkedNode;
}
function reverse(head: LinkedNode) {
if (!head.next) return head;
const newHead = reverse(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
|