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. When i write n.next , current getting affected, but why?
@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.
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.
So, if you use place next = current.next after n.next = prev then current = NULL and loop will stop iterating.
This is because n points to current only. 2 references are pointing to the same object and thus when you change n.next, changes are reflected in current.next as well
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.