题目名称:反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
解法
只会迭代
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
let pre = null
let cur = head
// * null 1---->2---->3---->4---->5---->NULL
// ? pre cur next
while (cur) {
let next = cur.next // 存储 节点 2 到 next 上
cur.next = pre // 更改节点 1 的 next 为 null
pre = cur // 存储节点 1 为 pre
cur = next
}
return pre
};
测试用例
// 测试用例
let test = {
val: 1,
next: {
val: 2,
next: {
val: 3,
next: null
}
}
}
console.time('执行用时');
console.log(reverseList(test));
console.timeEnd('执行用时');
总结
- 掌握链表这种数据结构的常见处理方式
- 虚拟头结点/尾结点
- 迭代
说明
- 本题解已同步leetcode-js-simple/01.[ 206 ] 反转链表,可以复制代码进行调试。
- 总结出了一套亲测有效的前端无痛刷题项目,有助于算法小白平稳入门,详见leetcode-js-roadmap,希望对从零开始刷题的前端小伙伴们带来帮助~
本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情