# 从一道前端面试题谈起

``const reverseList = (head, q = null) => head !== null ? reverseList(head.next, { val: head.val, next: q }) : q;``

## 单链表的数据结构

``````var reverseList = function(head) {
};``````
``````ListNode {
val: 1, next: ListNode {
val: 2, next: ListNode {
val: 3, next: [ListNode] } } }``````

## 循环迭代

``````var reverseList = function(head) {
let q = { val: p.val, next: null };
while (p.next !== null) {
p = p.next;
q = { val: p.val, next: q };
}
return q;
};``````

``````var reverseList = function(head) {
if (p === null) {
return null;
}
let q = { val: p.val, next: null };
while (p.next !== null) {
p = p.next;
q = { val: p.val, next: q };
}
return q;
};``````

## 递归

``````const reverseList = function(head) {
let q = null;
}
const r = function(p, q) {
if (p === null) {
return q;
} else {
return r(p.next, { val: p.val, next: q });
}
}``````

## 优化代码

``````const reverseList = function(head) {
let q = null;
}
const r = function(p, q) {
return p === null ? q : r(p.next, { val: p.val, next: q });
}``````

``````const reverseList = (head) => {
let q = null;
}
const r = (p, q) => {
return p === null ? q : r(p.next, { val: p.val, next: q });
}``````

``````const reverseList = (head) => {
let q = null;
}
const r = (p, q) => (p === null ? q : r(p.next, { val: p.val, next: q }));``````

``````const reverseList = (head, q) => r(head, q);
const r = (p, q) => (p === null ? q : r(p.next, { val: p.val, next: q }));``````

``````const reverseList = (head, q = null) => r(head, q);
const r = (p, q) => (p === null ? q : r(p.next, { val: p.val, next: q }));``````

``const reverseList = (head, q = null) => (head === null ? q : reverseList(head.next, { val: head.val, next: q }));``

12.4k 声望
4.4k 粉丝
0 条评论