题解 | #反转链表#
发表于 2022-02-08 11:03:21
1.第一步是找到当前节点的下一个节点,让定义的nex指针指向该节点, nex = cur.next 2.接下来要更换当前节点next的节点,使他反转往前指,这里既指向了一开始为空的pre的位置 cur.next = pre 3.第三步就是挪动cur指针和nex指针的位置,向后挪一位,以此循环,最终都是为了执行第二步,实现反转链表 pre = cur cur = nex 4.最终输出pre
注意⚠️,要判断一下头节点是不是大于1,小于等于1返回头节点本身就好,无需反转
/function ListNode(x){ this.val = x; this.next = null; }/ function ReverseList(pHead) { // write code here // 判断链表为空或长度为1的情况 if(pHead == null || pHead.next == null){ return pHead; } let p1 = null, p2 = null; while(pHead!=null){ // p1: 2->3->null p1 = pHead.next // pHead: 1->null pHead.next = p2 // p2: 1->null p2 = pHead // pHead: 2->3->null pHead = p1 } return p2
} module.exports = { ReverseList : ReverseList };