Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...