DEV Community

anjan-dutta
anjan-dutta

Posted on

Remove duplicates from an unsorted linked list [JavaScript]

// defining a linked list using nested object
let LL = {data: 1, next: {data: 2, next: {data: 3, next: {data: 1, next: {data: 2, next: {data: 5, next: null}}}}}};

let buffer = []; // an empty buffer to store values and check duplicates 
let HEAD = LL;  // pointing to top of the linked list.
let prev = null; // to store previous node 

while(HEAD != null) {
    if(buffer.indexOf(HEAD.data)>-1) {
        prev.next = HEAD.next;
    } else {
        buffer.push(HEAD.data);
        prev = HEAD;
    }
HEAD = HEAD.next;
}

console.log(LL);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)