题目描述:输入一个链表,反转链表后,输出新链表的表头。
输入一个链表,反转链表后,输出新链表的表头。
借助栈的后入先出的顺序,可以将顺序列表逆序。不过这不是原地反转,当然题目也没有要求。
处理过程如下:
时间复杂度 O(N),空间复杂度 O(N)。代码如下:
// ac地址:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
// 原文地址:https://xxoo521.com/2020-01-12-reverse-link/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
if (!head) {
return null;
}
const stack = [];
let node = head;
while (node) {
stack.push(node.val);
node = node.next;
}
const newHead = {
val: stack.pop(),
next: null
};
node = newHead;
while (stack.length) {
node.next = {
val: stack.pop(),
next: null
};
node = node.next;
}
return newHead;
};
“原地反转”的思路简单,但是实现起来有一些细节需要处理。链表类的原地操作,大部分都是细节上容易出错,导致死循环或者报错。
准备当前节点 node,和 node 的前一个节点 preNode。整体的思路如下:
时间复杂度是 O(N),空间复杂度是 O(1)。代码如下:
// ac地址:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
// 原文地址:https://xxoo521.com/2020-01-12-reverse-link/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
if (!head) {
return null;
}
let node = head;
let preNode = null;
while (node.next) {
const nextNode = node.next;
node.next = preNode;
preNode = node;
node = nextNode;
}
node.next = preNode;
return node;
};