Reputation: 27
I have few questions...
So I'm working with Single Linked List and I have some issues understanding the code. So let's say I have something like this:
public void addToEnd(int data)
{
Node p = start;
Node temp = new Node(data);
if (start == null)
{
start = temp;
return;
}
else
{
while(p.link != null)
{
p = p.link;
}
p.link = temp;
}
}
So... This code will add Node at the end of the list. I get that. Let's check the display list method...
public void displayList()
{
Node p = start;
if (start == null)
{
Console.WriteLine("List is empty.");
return;
}
while(p != null)
{
Console.Write("|" + p.data + "| -> ");
p = p.link;
}
}
So my concern is this... In displayList method, while loop says - ( while p != null ) ... I played with it a bit, and I changed it into - ( while p.link != null ). So result is that it wont print last element of the list. And so I got to conclusion that p.link is not last Node, but one before. It is just referring to the last Node of the list. So if my assumption is correct, how come that method addToEnd(int data) is working perfectly, and it's really adding some Node to the end if the wile loop in that method is - ( while p.link != null ). Shouldn't it like in case of displayList() method when I change the while loop point to the second last element of the list? If someone can explain this one to me that would be amazing. Thanks in advance guys ;)
Upvotes: 0
Views: 53
Reputation: 3829
Both methods are correct, let's break down the elements:
Node
class has a Link
property that links the next Node on the list (not the last)Now, how does displayList
work?
p
variable that will have the node that the method is working with at any given timep
, now that it's being assigned the start node, is empty, if it's empty a message is shown and the method ends, thenp
(the current element) is not null, print its value and then assign to p
the next element on the list, which is p.Link
while
exists and that's the endThe difference between the two methods is that addToEnd
checks if the next node is null to assign data
as the last element. displayList
can't move to the next element until it has printed the current one.
Upvotes: 1