js algorithm reverse linked list All In One
js algorithm reverse linked list All In One
reverse linked list / 反转链表
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
const head = new ListNode(1, 2);
head.next = new ListNode(2, 3);
// 递归
var reverseList = function(head) {
if (head == null || head.next == null) {
return head;
}
let temp = head.next;
let newHead = reverseList(temp);
temp.next = head;
head.next = null;
return newHead;
};
// 迭代
var reverseList = function(head) {
let newHead = new ListNode();
while(head) {
let temp = head.next;
head.next = newHead.next;
newHead.next = head;
head = temp;
}
return newHead.next;
};
const newHead = reverseList(head);
https://leetcode.com/problems/reverse-linked-list/description/
interview
python
refs
https://www.cnblogs.com/xgqfrms/tag/Algorithm/
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15374988.html
未经授权禁止转载,违者必究!