Home > Blockchain >  What does this else block in linkedlist add method code does?
What does this else block in linkedlist add method code does?

Time:06-19

public void Add(Node<T> newItem)
        {
            if(this.First==null)
            {
                this.First = newItem;
                this.Last = newItem;
            }
            else
            {
                newItem.next = this.First;
                this.First = newItem;
            }
            Count  ;
        }

Im Unable to understand how does else block actually works , as per my understanding newItem.next points to First node and then subsequently on next line we assign newItem to First , im finding it hard how does this condition works and how new node is added in case of if there exists node previously ..

CodePudding user response:

if the list's first item is null, which means the list is empty, it set's first and the last (since it's the only item, it will be first and the last item) item to the newItem.

Or else, it links the first item to the new item as its next node, and sets the first item to the newItem. It simply puts newItem in the beginning of the list, then links former first item to it.

CodePudding user response:

It would be a bit difficult to explain without some graphics but let me give it a try.

  1. Initially, our linked list is empty. First-> NULL
  2. Then we add a new item by calling Add, say Item1.
  3. Because this.First is null, it will start pointing to this newItem. Remember, First here is nothing but a pointer pointing to the newItem now. So our linked list now is: First -> Item1
  4. Now we add another item but this time the linked list is not empty. Say, Item2
  5. Looking at the code, the intention is to add the new item at the beginning of the linked list. So, we make the next pointer of the newItem point to First making them linked to each other. Our linked list now is: Item2.next -> First
  6. Now because we only want to maintain the First (head) pointer we point it to the current first/ or head node which is nothing but the newly added item. Hence this.First = newItem.

Linked list now is: Item2 -> Item1 with First pointing to Item2.

  • Related