簡體   English   中英

我已經使用堆棧(stl)來找到兩個鏈表的交點,但是我遇到了分段錯誤,下面是我的 function,

[英]I have used stack (stl) to find the intersection point of the two linked list ,but I am getting segmentation fault, below is my function,

包含所有頭文件,我必須返回找到交叉點的節點的數據

int findMergeNode(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2){
    
    stack<int>s1;
    stack<int>s2;
    int ans;
    while(head1!=NULL)
    {
        int x=head1->data;
        s1.push(x);
        head1=head1->next;
    }
    while(head2!=NULL)
    {
        int x=head2->data;
        s2.push(x);
        head2=head2->next;
    }
    while(s1.top()==s2.top())
    {
        ans=s1.top();
        s1.pop();
        s2.pop();
    }
    
    return ans;
}

至少這個while循環

while(s1.top()==s2.top())
{
    ans=s1.top();
    s1.pop();
    s2.pop();
}

可以調用未定義的行為,因為您沒有檢查堆棧之一是否已經為空。

此外,最初變量ans未初始化,function 可以返回不確定的值。

請注意,由於列表本身在 function 中沒有更改,因此 function 應聲明為

int findMergeNode( const SinglyLinkedListNode* head1, const SinglyLinkedListNode* head2 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM