Hello Guys I know it is not the good way to write Queue but I want to understand this thing
here in my code I have a Node
Class and there is just (int data
and Node Next
) inside it.
in other class, I am doing this
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
Node temp = head;
temp.next.next.next = new Node(4);
Console.WriteLine(head.data + "\n" + head.next.data + "\n" + head.next.next.data + "\n"+head.next.next.next.data);
I am getting this output.
1
2
3
4
I want to understand why head
printing found the last node which I create in Temp
can someone understand me and tell me why?
Node Temp
just copied head
and added a new Node which is 4
but what makes this last node appear in head
?.
You need to understand the reference types for this. So a class/object is a reference type .
A reference type ,extends System.Object and points to a location in the memory that contains the actual data.
So when you said Node temp=head`.
Now both of the object point to same location and any changes in one will change the other
https://www.tutlane.com/tutorial/csharp/csharp-value-type-and-reference-type-with-examples
https://www.infoworld.com/article/3043992/a-deep-dive-value-and-reference-types-in-net.html
So first of all new keyword always creates new object.So as you can see temp and head are same when you assign head= temp
As soon as you say , temp=temp.next
, now it will point to next node and now head and temp will not be same.Temp will point to the next node of head
Now as soon as you write temp = new Node("10");
it creates new object and assign to temp.So new key word always creates new object
But if you do like this temp.Data="10" without doing temp=new Node("10");, it will change both head and temp