示例:
1->2->3->4->5->null
5->4->3->2->1->null
js中模拟链表
const a = { val: 'a' } const b = { val: 'b' } const c = { val: 'c' } const d = { val: 'd' } a.next = b b.next = c c.next = d //遍历链表 let p = a //point while (p) { console.log(p.val) p = p.next } // 插入一个e节点 const e = { val: 'e' } c.next = e e.next = d // 删除e节点 c.next = d
解题思路:
1. 先思考如何反转2个节点,将n+1的next指向n
2. 双指针遍历链表,然后重复上面的动作
解题步骤:
1. 双指针遍历
2. 反转双指针
var reverseList = function (head) { let p1 = head let p2 = null while (p1) { const tmp = p1.next p1.next = p2 p2 = p1 p1 = tmp } return p2 };