[英]Bug in Reversing Linked List
Can a pointer be altered when we are altering another pointer pointing to same address 当我们改变指向同一地址的另一个指针时,是否可以改变指针
Code for reversing Linked List 扭转链表的代码
Node Reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
Node n = null;
while (current != null) {
n = current;
next = current.next; //this works
n.next = prev;
// next = current.next; //this does not
prev = n;
current = next;
}
node = prev;
return node;
}
Doubt: How can Node n affect the node current. 疑问: Node n如何影响节点电流。 When i write n.next , current getting affected, but why?
当我写n.next时,当前受到影响,但为什么呢?
@Gaurav Anand @Gaurav Anand
Yes, it does affect the value of current because Node current and n has the same address and any changes made to either of the variable will be reflected in both as value at address will change. 是的,它确实会影响当前值,因为节点当前和n具有相同的地址,并且对任一变量所做的任何更改都将反映在地址中的值将更改。
In your code: 在你的代码中:
When next = current.next is placed after n.next = prev it doesn't works because you have changed the value of n.next which is same as current.next to NULL (prev = NULL) as the Node current and n has same address. 当next = current.next放在n.next = prev之后它不起作用,因为你已经将n.next的值与current.next相同改为NULL(prev = NULL),因为Node current和n有同一地址。
So, if you use place next = current.next after n.next = prev then current = NULL and loop will stop iterating. 因此,如果在n.next = prev之后使用place next = current.next,则current = NULL并且循环将停止迭代。
This is because n points to current only. 这是因为n仅指向当前。 2 references are pointing to the same object and thus when you change n.next, changes are reflected in current.next as well
2个引用指向同一个对象,因此当您更改n.next时,更改也会反映在current.next中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.