首页 > 解决方案 > 为什么将一个指针分配给另一个指针会改变 cpp 中的原始指针?

问题描述

假设 headA 指向 [1, 3, 5, 7, 9, 11],headB 指向 [2, 4 ,9, 11]。我想找到常见的相交元素问题陈述

我不明白为什么a_pointerb_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);
        
    }

标签: c++pointerslinked-list

解决方案


我不明白为什么赋值 a_pointer = headB 正在改变原来的 headB 指针。

不理解为什么会改变原来的 headB 指针是合理的,因为原来的 headB 指针并没有被改变。


推荐阅读