This is the implementation of a node I was given to work with:
public class IntNode
{
private int value;
private IntNode next;
public IntNode(int value)
{
this.value = value;
this.next = null;
}
public IntNode(int value, IntNode next)
{
this.value = value;
this.next = next;
}
public int GetValue()
{
return value;
}
public IntNode GetNext()
{
return next;
}
public void SetValue(int value)
{
this.value = value;
}
public void SetNext(IntNode next)
{
this.next = next;
}
public override String ToString()
{
return value + "-->" + next;
}
}
As for addition to the beginning of a list - I've been given a code that adds the node q to the beginning of a list which begins with the node first. That's the code:
IntNode q = new IntNode(value);
q.SetNext(first);
first=q;
The thing is, I don't understand why is the last line necessary. Why should first point to q's value? If we want to add q to the list, shouldn't we just make it point to the original first node? I've looked up in several websites about this algorithm and they all treat this line as an obvious without explaining why. I tried to add a new node to the beginning of a list while intentionally omitting this line, and it worked perfectly well (By printing the list to the console, I've seen that q became the first node before first).
If someone could explain it, I'd be glad :)
(I'm only a novice programmer, so I apologize ahead for any mistakes I might have had).
答案 0 :(得分:2)
When you add a node q
at the head of a list, two things happen:
q
q
becomes the first node.By doing this:
q.SetNext(first);
you are just performing number 1. You also need to perform number 2 to make q
be the first, so
first = q;
shouldn't we just make it point to the original first node?
You mean just doing the second line?
If you do this, the variable first
now refers to the second node (the actual first is q
now!), which makes no sense.
答案 1 :(得分:0)
Why should first point to q's value
Because we are adding node to the start of the list so it should be the first node now in our Linked List. q
is a new node added and we set it's next node to the first
, that is fine, but now our first
element is q
as your adding an element to the front of the linked list which means here is at the start of the linked list.
You can adjust your code like following with better variable names to get easy understanding, and this is what you actually want i guess:
IntNode newNode = new IntNode(value); //create elemeent
currentNode.SetNext(newNode); // add it next to current element
currentNode = newNode; // now newNode is CurrentNode as next element will be linked with newNode
Hope it helps.