c++ - 为什么将一个指针分配给另一个指针会改变 cpp 中的原始指针?
问题描述
假设 headA 指向 [1, 3, 5, 7, 9, 11],headB 指向 [2, 4 ,9, 11]。我想找到常见的相交元素问题陈述
我不明白为什么a_pointer
,b_pointer
最后返回一个空列表。
我跟着这个教程
遵循的算法:(如下)
#include<bits/stdc++.h>
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *head) { val = x; next = head; }
};
class Solution {
public:
void print(ListNode *head)
{
while(head != nullptr)
{
printf("%d ->", head->val );
head = head->next;
}
printf("\n");
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
print(headA);
print(headB);
ListNode *a_pointer, *b_pointer;
a_pointer = headA;
b_pointer = headB;
while(a_pointer != b_pointer)
{
if(a_pointer == nullptr)
{
a_pointer = headB;
}
else
{
a_pointer = a_pointer->next;
}
if(b_pointer == nullptr)
{
b_pointer = headA;
}
else
{
b_pointer = b_pointer->next;
}
}
print(a_pointer);
print(b_pointer);
return a_pointer;
}
};
int main()
{
Solution s;
ListNode *node1 = new ListNode(1);
node1->next = new ListNode(3);
node1->next->next = new ListNode(5);
node1->next->next->next = new ListNode(7);
node1->next->next->next->next = new ListNode(9);
node1->next->next->next->next->next = new ListNode(11);
ListNode *node2 = new ListNode(2);
node2->next = new ListNode(4);
node2->next->next = new ListNode(9);
node2->next->next->next = new ListNode(11);
ListNode *ret = s.getIntersectionNode(node1,node2);
}
解决方案
我不明白为什么赋值 a_pointer = headB 正在改变原来的 headB 指针。
不理解为什么会改变原来的 headB 指针是合理的,因为原来的 headB 指针并没有被改变。
推荐阅读
- react-native - React Native Multiple fetch vs Filter
- node.js - 在 mac 上“nvm 使用”后节点版本未更新
- linux - SSH 权限被拒绝(公钥)
- ansible - 从 gitlabci 运行 Ansible playbook 命令
- asp.net - 如何在 asp.net core 中获取用户 ID?
- c - 二进制搜索计数器未更新
- javascript - 如何修复这个 jQuery 故障,以便在使用 .hover() 时 div 不会尝试消失?
- angular - Angular Generate component through path has already exists错误
- php - PHP 致命错误:在第 87 行的 /var/www/html/FW/access_check.php 中的 null 上调用成员函数 stmt_init()
- java - 当用户删除应用快捷方式时如何更改共享偏好