本人题解:
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
function ReverseList( head ) {
// write code here
let prev = null;
let cur = head;
while(cur){
const temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}
module.exports = {
ReverseList : ReverseList
};
注意在本地vscode调试时,如果需要构造ListNode类型则可以:
function ListNode (val){
this.val = val;
this.next = null;
}
/*多次构造链表*/
// 透节点
let head = new ListNode(1)
// 头指针
let cur = head
for(let i = 1;i < 6;i++){
cur.next = new ListNode(i+1);
cur = cur.next;
}
// 输出链表
console.log('head',head)
当然也可以用对象数据类型模拟链表,如:
const head = {
val;1,
next:{
val:2,
next:{
val:3
next: null
}
}
}