简体   繁体   中英

C++ node assign error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

I am learning DSA , Linked List , new to C++. My linked list is of exception.

Error Info:

错误

It is much longer than it should be.

在此处输入图片说明

Here is my code:

define struct ListNode

// Definition for singly-linked list.
struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

get Intersection of Two Linked Lists

 ListNode * Solution_three :: getIntersectionNode(ListNode *headA, ListNode *headB) {

    ListNode * p_one = headA;
    ListNode * p_two = headB;

    if (p_one == NULL || p_two == NULL) {
        return NULL;
    }

    while (p_one != NULL && p_two != NULL && p_one != p_two) {
        p_one = p_one -> next;
        p_two = p_two -> next;


        if( p_one == p_two ){
            return p_one;
        }

        if (p_one == NULL) {
            p_one = headB;
        }
        if (p_two == NULL) {
            p_two = headA;
        }
    }
    return p_one;
}

construct samples and call Intersection of Two Linked Lists

void Solution_three :: test_Intersection(){

    ListNode *node_one = new ListNode(1);
    ListNode *two = new ListNode(3);
    ListNode *three =  new ListNode(5);
    ListNode *four =  new ListNode(7);
    ListNode *five =  new ListNode(9);
    ListNode *six =  new ListNode(11);

    node_one->next = two;
    two->next = three;
    three->next = four;
    four->next = five;
    five->next = six;


    ListNode *node_a_one = new ListNode(2);
    ListNode *a_two = new ListNode(5);
    ListNode *a_three = new ListNode(9);
    ListNode *a_four = new ListNode(19);
    node_a_one->next = a_two;
    a_two->next = a_three;
    a_three->next = a_four;


    ListNode node_r = *getIntersectionNode(node_one, node_a_one);
    printf("%d", node_r.val);
    cout<<"\n"<<node_r.val<<endl;
}

By take a break point, I see the linked list is much longer.

I don't know how to take it out.

How could p_one != p_two be true.

Should overload the operator != , to compare the value of the node.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM