利用栈,先把元素都压入栈中,再建立一个头结点HeadNode,放入第一个出栈元素,这个头结点保持不动,方便后续返回链表,新建一个工具指针cuur,用来将元素依次从栈中取出存入链表,用完之后他就没用了,用始终指向最前面的HeadNode来输出链表
this.val = x;
this.next = null;
}*/
function ReverseList(pHead) {
// write code here
if (pHead == null || pHead.next == null) return pHead;
var stack = [];
//压栈
while (pHead != null) {
stack.push(pHead);
pHead = pHead.next;
}
var headNode = stack.pop();
var curr = headNode;
while (stack.length) {
curr.next = stack.pop();
curr = curr.next;
curr.next = null;
}
return headNode;
}
module.exports = {
ReverseList: ReverseList,
};

京公网安备 11010502036488号