题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
1. 思路分析
创建链表是将节点依次插入到链表尾部,而反转链表的话,只需要将节点取出来放到头部。为了方便可以做一个哨兵节点,每次将节点插入到后即可,最后返回。
2. 代码实现
function ListNode(x){
this.val = x;
this.next = null;
}
function ReverseList(head) {
if(!head || !head.next) return head;
const dummy = new ListNode();
let cur = head;
while(cur) {
if(cur == head) {
dummy.next = new ListNode(cur.val);
}else {
let node = new ListNode(cur.val);
node.next = dummy.next;
dummy.next = node;
}
cur = cur.next
}
return dummy.next;
}
module.exports = {
ReverseList: ReverseList,
};