2017-07-24 49 views
0

我正在研究这个在hackerrank上查找合并节点的方法。我的方法是:当两个节点都不为空时,我想将其中一个列表移动到它们的下一个节点,这是flag变量的用途。但不知何故,它给我分段错误?我是否意外地访问了一个空变量?有人请赐教。以下是我的方法代码。查找合并节点时发生分段错误?

约束:这两个列表将收敛和两个列表都是非NULL

int FindMergeNode(Node *headA, Node *headB) 
{ 
    // Complete this function 
    // Do not write the main method. 
    bool flag = true; 
    while(headA != headB){ 
     if(flag) headA=headA->next; 
     else headB=headB->next; 
     flag = !flag; 
    } 

    return headA->data; //or headB->data; 
} 
+1

为什么不看你的调试器? –

+0

你永远不会检查'headA'或'headB'是否为'NULL'。试图从'(NULL) - > next'读取将会调用未定义的行为。 – Havenard

+0

我之前检查过,并试图缩短我的代码,并把它放在while循环中。谢谢,我会在我的代码中修复它。 –

回答

3

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

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

+0

是的,约束表明两个节点都不是NULL,它们也会收敛。 Thx指出,我会把它放在问题上。两个肯定是我失败的原因。谢谢! –

1

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

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; 
} 
+0

thx,我看到我错过了。 –

+0

L. Dai请确认是否有用 –

相关问题