describe

Given a sorted linked list, remove all duplicate elements so that each element appears only once.

The sample

Example 1:

Enter 1->1->2 => 1->2

Input: 1->1->2->3 => 1->2->3

Input: 1->2-1->4 => 1->2->4

Train of thought

Delete to find the previous node

code

function ListNode(val){
    this.val = val
    this.next = null
}

const p1Node1 = new ListNode(1)
const p1Node2 = new ListNode(2)
const p1Node3 = new ListNode(1)
const p1Node4 = new ListNode(4)

p1Node1.next = p1Node2
p1Node2.next = p1Node3
p1Node3.next = p1Node4



function deleteNode(p1) {
    const cache = {}
    let last = new ListNode() // the previous node
    let cur = p1
    
    while(cur ! = =null) {
        if(! cache[cur.val]) { last.next = cur.next }else {
            cache[cur.val] = true
            last = cur
        }
        cur = cur.next
    }
    
    return p1 
}

deleteNode(p1Node1)

Copy the code