通过迭代方式
function reverseList(head) { // a -> b -> c -> null // c -> b -> a -> null let prev = null; let cur = head; while (cur) { const next = cur.next; // 获取下一个节点 cur.next = prev; // 当前节点指向上一个节点 prev = cur; // 存储上一个节点 cur = next; // 更新当前节点 } return prev;}
通过递归方式
function reverseList(head) { // a -> b -> c -> null // c -> b -> a -> null if (!head || !head.next) { return head; // 返回最里面的一个节点 } const newHead = reverseList(head.next); // 从内到外执行(获取最里面的一个节点) head.next.next = head; head.next = null; // 解除环引用 return newHead;}