I have 3 pointers:
Node* head;
Node* temp=head;
Node* p=new Node(2);
Now I assign:
temp->next=p
Will the next of head will also be changed?
head->next=?
CodePudding user response:
Yes, if head
would actually point at some allocated memory, temp
would point to the same memory.
Example:
#include <iostream>
struct Node {
Node(int X) : x(X) {}
int x;
Node* next;
};
int main() {
Node* head = new Node(1);
Node* temp = head; // temp points to the same memory as head
Node* p = new Node(2);
temp->next = p; // head->next is the same as temp->next
std::cout << head->next->x << '\n' // prints 2
delete head;
delete p;
}