【问题标题】:Code to Find the Merge Point of Two linked Lists查找两个链表的合并点的代码
【发布时间】:2017-11-29 14:42:16
【问题描述】:

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

【问题讨论】:

  • 我建议您在单步执行代码时使用调试器并绘制列表。
  • 你应该找出代码出了什么问题。它不编译吗?它不链接吗?错误信息是什么?它会崩溃吗?哪条线?它会产生不正确的结果吗?它产生了哪些结果,您期望得到哪些结果?我们如何重现该问题?
  • 您是否被允许破坏原始列表的结构?
  • 在你的上下文中合并是什么真的不清楚。这个用户将如何处理合并点?
  • 你为函数赋予了哪些值?它给出了哪个答案?哪个答案是正确的?

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


【解决方案1】:

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。然后,您的逻辑检查 nextPTRL(指向 6)是否等于 nextPTRS(指向 6)。如果它们相等(它们相等,因为它们都指向 6),则该方法返回 dataPTRL,此时为 5

将while循环中的条件更改为PTRL != PTRS,我认为这应该可以解决您的问题。

【讨论】:

  • 或者我可以返回 PTRL->next->data
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 2017-09-07
  • 1970-01-01
  • 2019-07-22
  • 2021-02-26
相关资源
最近更新 更多