Skip to content
Advertisement

Creating a linked list object using js

I want to make a linked list using custom Object that pushes a value, pop a value, display all its content, remove an item from a specific place, and insert at a specific place as long as the value is missing from the sequence otherwise through an exception. All of the properties should be defined using data descriptor, prevent them from being deleted, iterated, or being modified.

I can do no more than this … I’m new to js.

        var linkedList = {};

       /* linkedList.name = 'Ahmed';
        [].push.call(linkedList, 'sad', "sd");
*/
        Object.defineProperty(linkedList, "name", {
            value: "mohamed",
            writable: false,
            configurable: false,
            enumerable: false
        })
        linkedList.next = {'sd':'as'};

Any help? thanks in advance

Advertisement

Answer

In a linked list it’s only really important to know where the head & the tail are. So I’d suggest something like this:

function createLinkedList(firstvalue) {
  const link = {
    value: firstvalue
    next: null
  };
  return {
    head: link,
    tail: link
  }
}

function addToLinkedList(linkedList, value) {
  const link = {
    value,
    next: null
  }
  linkedList.tail.next = link;
  linkedList.tail = link;
}

let linkedList = createLinkedList("mohamed");
linkedList = addToLinkedList(linkedList, "anotherName");

This is just a concept, you’ll have to apply it to your code obviously.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement