【算法题】反转链表(js)

牛客链接:https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=196&&tqId=37111&rp=1&ru=/ta/job-code-total&qru=/ta/job-code-total/question-ranking

在这里插入图片描述
本人题解:

/*
 * 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;1next:{
	 	val:2,
	 	next:{
	 		val:3
	 		next: null
	 	}
	 }
}
  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

godlike-icy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值