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)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay