# 从一道前端面试题谈起

``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 p = 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) {
let p = 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 }));``

#### 你可能感兴趣的

4 条评论
binave · 6月1日

leetcode我都是先用js或者shell快速测试思路，没问题了再翻译成其他语言填到答案里。脚本语言用文本编辑器就可以操作，算法题一般也用不上什么api……

1->2->3->4->5->NULL:1->NULL 和 2->3->4->5->NULL； 2->1->NULL 和 3->4->5->NULL 以此类推，当原始链表的next == null 的时候，遍历结束。完成翻转。

hehe · 6月13日