Creating a LinkedList class from scratch

后端 未结 11 757
慢半拍i
慢半拍i 2020-12-02 06:52

We were given an assignment to create a LinkedList from scratch, and there are absolutely no readings given to guide us on this migrane-causing task. Also everything online

11条回答
  •  爱一瞬间的悲伤
    2020-12-02 07:12

    Sure, a Linked List is a bit confusing for programming n00bs, pretty much the temptation is to look at it as Russian Dolls, because that's what it seems like, a LinkedList Object in a LinkedList Object. But that's a touch difficult to visualize, instead look at it like a computer.

    LinkedList = Data + Next Member

    Where it's the last member of the list if next is NULL

    So a 5 member LinkedList would be:

    LinkedList(Data1, LinkedList(Data2, LinkedList(Data3, LinkedList(Data4, LinkedList(Data5, NULL)))))

    But you can think of it as simply:

    Data1 -> Data2 -> Data3 -> Data4 -> Data5 -> NULL

    So, how do we find the end of this? Well, we know that the NULL is the end so:

    public void append(LinkedList myNextNode) {
      LinkedList current = this; //Make a variable to store a pointer to this LinkedList
      while (current.next != NULL) { //While we're not at the last node of the LinkedList
        current = current.next; //Go further down the rabbit hole.
      }
      current.next = myNextNode; //Now we're at the end, so simply replace the NULL with another Linked List!
      return; //and we're done!
    }
    

    This is very simple code of course, and it will infinitely loop if you feed it a circularly linked list! But that's the basics.

提交回复
热议问题