Hi,大家好,我是小庄。
今天打卡的算法题是 —— LeetCode 206.反转链表
该题将采用「迭代法」和「递归法」分别实现
话不多说,一起来学习吧~
一、Leetcode题目 1、题目地址点击查看Leetcode题目
2、具体题目
(1)具体代码
var reverseList = function(head) {
let pre = null;
let cur = head;
let next = head;
while(cur !== null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
};
(2)运行结果
2、方法:递归法;
(1)具体代码
var reverseList = function(head) {
if(head === null || head.next === null) {
return head;
}
let res = reverseList(head.next);
head.next.next = head;
head.next = null;
return res;
};
(2)运行结果
3、补充部分
注:以下为手动构建完整链表,并采用迭代法实现。
function ListNode(val) {
this.val = val;
this.next = null;
}
function createList(n) {
let head = null;
while(n) {
let tempNode = new ListNode(n);
tempNode.next = head;
head = tempNode;
n--;
}
return head;
}
let head = createList(3);
console.log(head);//1->2->3
function getReverseList(head) {
let pre = null;
let cur = head;
let next = head;
while(cur !== null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
let res = getReverseList(head);
console.log(res);//3->2->1
三、讲解视频
点击查看B站讲解视频
四、补充部分关注公众号:【深漂程序员小庄】:
内含丰富的学习资源和面试经验(不限前端、java),还有学习交流群可加,并且还有各大厂大佬可一起交流学习,一起进步~添加小庄微信,回复【加群】,可加入互联网技术交流群。
本文由mdnice多平台发布



