这个点之前一直很混淆,今天碰巧看了个题,记录一下。
对于node* p = a;此时p与a的地址一样,那么p发生变化时a是不是也变化了呢?发现有两种不一样的情况:
如果p = p->next;此时p变化了,a没有变化,对于p->next = b;此时p->next变化了,a->next也变化了。
例子:
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
int main()
{
ListNode* p1 = new ListNode(1);
ListNode* p2 = new ListNode(2);
ListNode* p3 = new ListNode(3);
ListNode* p4 = new ListNode(4);
ListNode* p5 = new ListNode(5);
p1->next = p2;
p2->next = p3;
p3->next = p4;
p4->next = p5;
p5->next = nullptr;
ListNode* p7 = p1;
cout << "before change p7:" << p7 << "," << p1<<endl;
p7 = p7->next;
cout <<"p1->val"<< p1->val<<"\n";
cout << "p7->val"<<p7->val<<"\n";
cout << "after change p7 p7 = p7->next;" <<"p7"<< p7 << "," << "p1"<<p1<<endl;
ListNode* p8 = p1;
cout << "before change p8:" << p8->next->val << "p1:" << p1->next->val << endl;
p8->next = p4;
cout << "agter change p8->next = p4:" <<"p8->next->val "<< p8->next->val << " p1->next->val:" << p1->next->val << endl;
p8 = p5;
cout << "after p8=p5" << "p8:" << p8 << "p1:" << p1 << endl;
}
可以看出来,p8本身发生变化时不会影响p1;但p8->next指向另外的节点时,p1也会跟着变化。
原因有待深究,。