找到合并节点时出现分段错误?

时间:2017-07-24 22:49:59

标签: c++ data-structures merge linked-list nodes

我正在hackerrank上查找此查找合并节点方法。我的方法是:当两个节点都不为空时,我想将其中一个列表移动到它们的下一个节点,这就是标志变量的用途。但不知怎的,它给了我分段错误?我是否偶然访问了一个null变量?有人请赐教。下面是我的方法代码。

约束:两个列表都会收敛,两个列表都是非NULL

$ export LC_ALL=pt_PT.utf8 
$ export LANG="$LC_ALL"

2 个答案:

答案 0 :(得分:3)

你做了两个假设:
1.存在这样的节点 2.此节点距每个列表开头的距离在两个列表之间最多相差1。您可以在一个列表中交替前进,然后检查是否到达同一节点(按地址)。因此,如果list1在您要查找的节点之前没有节点,并且list2之前有2个节点,则您将找不到匹配项。

如果我正确理解你的问题,事实是距离列表末尾的距离是相同的(因为它们的尾巴是相同的)。

答案 1 :(得分:1)

为什么直接使用flag使用条件来检查它是否是最后一个节点

if(headA->next ==NULL) 
headA=headA->next; 
else if (headB->next== NULL )
headB=headB->next; 

完整的解决方案将是

int FindMergeNode(Node *headA, Node *headB) {
    Node *currentA = headA;
    Node *currentB = headB;

    //Do till the two nodes are the same
    while(currentA != currentB){
        //If you reached the end of one list start at the beginning of the other one
        //currentA
        if(currentA->next == NULL){
            currentA = headB;
        }else{
            currentA = currentA->next;
        }
        //currentB
        if(currentB->next == NULL){
            currentB = headA;
        }else{
            currentB = currentB->next;
        }
    }
    return currentB->data;
}
相关问题