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.
- Initially, our linked list is empty. First-> NULL
- Then we add a new item by calling
Add
, say Item1. - Because
this.First
is null, it will start pointing to thisnewItem
. Remember,First
here is nothing but a pointer pointing to thenewItem
now. So our linked list now is: First -> Item1 - Now we add another item but this time the linked list is not empty. Say, Item2
- 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 thenewItem
point toFirst
making them linked to each other. Our linked list now is: Item2.next -> First - 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. Hencethis.First = newItem
.
Linked list now is: Item2 -> Item1 with First pointing to Item2.