关于队列数据结构
About Queue Data Structure
大家好,我知道这不是写队列的好方法,但我想了解这个东西
在我的代码中,我有一个 Node
Class,里面只有 (int data
和 Node Next
)。
其他class,我正在做这个
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);
我得到这个输出。
1
2
3
4
我想了解为什么 head
打印找到我在 Temp
中创建的最后一个节点
有人能理解我并告诉我为什么吗?
Node Temp
刚刚复制了 head
并添加了一个新节点 4
但是是什么让最后一个节点出现在 head
中?
您需要为此了解引用类型。所以 class/object 是引用类型 .
引用类型,扩展 System.Object 并指向内存中包含实际数据的位置。
所以当你说 Node temp=head` 时。
现在两个对象都指向同一个位置,一个中的任何更改都会更改另一个
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
所以首先 new 关键字总是创建新的 object.So 因为当你分配 head= temp
时你可以看到 temp 和 head 是相同的
你一说,temp=temp.next
,现在它会指向下一个节点,现在head和temp不会same.Temp会指向head的下一个节点
现在只要你写 temp = new Node("10");
它就会创建新对象并分配给 temp.So new 关键字总是会创建新对象
但是如果你这样做
temp.Data="10" 不做 temp=new Node("10");,它会同时改变 head 和 temp
;
大家好,我知道这不是写队列的好方法,但我想了解这个东西
在我的代码中,我有一个 Node
Class,里面只有 (int data
和 Node Next
)。
其他class,我正在做这个
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);
我得到这个输出。
1
2
3
4
我想了解为什么 head
打印找到我在 Temp
有人能理解我并告诉我为什么吗?
Node Temp
刚刚复制了 head
并添加了一个新节点 4
但是是什么让最后一个节点出现在 head
中?
您需要为此了解引用类型。所以 class/object 是引用类型 .
引用类型,扩展 System.Object 并指向内存中包含实际数据的位置。
所以当你说 Node temp=head` 时。
现在两个对象都指向同一个位置,一个中的任何更改都会更改另一个
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
所以首先 new 关键字总是创建新的 object.So 因为当你分配 head= temp
时你可以看到 temp 和 head 是相同的你一说,temp=temp.next
,现在它会指向下一个节点,现在head和temp不会same.Temp会指向head的下一个节点
现在只要你写 temp = new Node("10");
它就会创建新对象并分配给 temp.So new 关键字总是会创建新对象
但是如果你这样做 temp.Data="10" 不做 temp=new Node("10");,它会同时改变 head 和 temp