Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

javascript - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...