查找两个链接列表的合并点的代码

时间:2017-11-29 14:42:17

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

FindMergePoint()的转发声明

int FindMergePoint(Node *Larger,int largeCount,Node *Smaller,int SmallCount);

根据大小计算两个列表长度的函数将列表传递给FindMergePoint(),它将返回交集节点。

    int FindMergeNode(Node *headA, Node *headB)
    {
        Node *PTRA = headA;
    Node *PTRB = headB;
    int count1 = 0,count2 = 0;
    //Count List One
    while(PTRA != NULL){
        count1++;
        PTRA = PTRA->next;
    }
    //Count List Two
    while(PTRB != NULL){
        count2++;
        PTRB = PTRB->next;
    }
    //If First list is greater
    if(count1 >= count2){
        return FindMergePoint(headA,count1,headB,count2);
    }
    else{//Second is greater
        return FindMergePoint(headB,count2,headA,count1);
    }
}

获取更大和更小的列表并查找合并点的函数

 int FindMergePoint(Node *Larger,int largeCount,Node *Smaller,int SmallCount){
    Node *PTRL = Larger;
    //Now traversing till both lists have same length so then we can move 
parallely in both lists
    while(largeCount != SmallCount){
        PTRL = PTRL->next;
        largeCount--; 
    }
    Node *PTRS = Smaller;
    //Now PTRL AND PTRS WERE SYNCHRONIZED
    //Now,Find the merge point     
    while(PTRL->next != PTRS->next){
        PTRL = PTRL->next;
        PTRS = PTRS->next;
    }
    return PTRL->data;
}

1 个答案:

答案 0 :(得分:0)

FindMergeNode处的代码块导致问题

while(PTRL->next != PTRS->next) {
    PTRL = PTRL->next;
    PTRS = PTRS->next;
}

我们有PTRLPTRS

的以下条目
PTRL -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8
PTRS -> 17 -> 6 -> 7 -> 8

现在,根据您的实施,PTRL将提前 4次  (较小的链表的长度)并指向5。然后,您的逻辑检查next PTRL(指向6)是否等于next PTRS(指向6)。如果它们相等(因为它们都指向6),则该方法返回data的{​​{1}},此时为PTRL

将while循环中的条件更改为5,我认为这可以解决您的问题。