gpt4 book ai didi

c - 链表交点程序的改进

转载 作者:行者123 更新时间:2023-11-30 14:47:07 25 4
gpt4 key购买 nike

我编写了下面的代码来查找链接列表的交点。有人可以检查一下并告诉我是否可以做任何改进以使其变得更好。

算法-:

  1. 取两个指针p1和p1,分别在LL-1和LL-2的头部初始化。然后让它们都遍历列表,一次一个节点。
  2. 当 p1 到达列表末尾时,将其重定向到 LL-2 的头部,而当 p2 到达列表末尾时,将其重定向到 LL-1 的头部。
  3. 如果在任意点 p1 与 p2 相交,则 p1/p2 是交集节点。

    int getIntesectionNode(struct Node* head1, struct Node* head2)
    {
    struct Node *start1 = head1;
    struct Node *start2 = head2;

    bool endFound1 = false;
    bool endFound2 = false;

    if( start1 == NULL || start2 == NULL)
    {
    return -1;
    }

    while(1)
    {
    start1 = start1->next;
    start2 = start2->next;

    if( start1 != start2)
    {
    if( start1 == NULL)
    {
    if (endFound1)
    {
    printf("Intersection not found !");
    break;
    }
    start1 = head2;
    endFound1 = true;
    }

    if( start2 == NULL)
    {

    if (endFound2 )
    {
    printf("Intersection not found !");
    break;
    }
    start2 = head1;
    endFound2 = true;
    }
    }
    else
    {
    printf("Intersection point found\n");
    printf("%d",start1->data);
    return start1->data;
    }
    }
    return -1;
    }

最佳答案

我想我不明白,但如果你按照我的想法做,我会使用第二个循环,并检查每个 LL-2 的所有 LL-1。我还会检查平等的起点在开始循环并进入下一个点之前,不检查它直到循环。

关于c - 链表交点程序的改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51582840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com