arrays - 查看两个链表是否相等的算法

标签 arrays algorithm linked-list

我有一个算法比较两个链表 L1 和 L2,以及相等的元素,它将它们放在第三个列表 L3 中,同时从 L2 中删除它们。我不确定这是否就是算法应该做的全部,而且我不理解一些概念,例如“p1prec”。我想理性地了解算法的设计,大局观。当我试图通过一条一条地检查说明来理解它时,我觉得我在努力记住它。也欢迎就设计相似算法的方法提出一些建议。算法如下:

    Equal(L1,L2)

    head[L3] = NIL            //L3 is empty
    if head[L2] = NIL         //if there are no elements in L2 return NIL
       return L3
    p1 = head[L1]             //p1 points the head of L1
    p1prec = nil              //p1prec is supposed to be precedent I guess.
    while p1 =/= nil
          p2 = head[L2]       //p2 points head of L2
          p2prec = nil        //p2prec is precedent of p2; first cycle is nil
          while p2 =/= nil and key[p1] =/= key[p2]
                p2prec = p2          // pass p2 and p2prec through L2 until
                p2 = next[p2]        // key[p1] = key[p2]
          if p2 =/= nil        // if two elements are found equal
                next[p1prec] = next[p1]          // im not sure what this does
                insert(L3,p1)                    // insert the element in L3
                p1 = next[p1prec]                //neither this,
                next[p2prec] = next[p2]  //connects the p2prec with nextp2 because p2
                free(p2)                         //is going to be deleted
          p1prec = p1      //moves through L1, if no element of p2 is found          
          p1 = next[p1]                         //equal with first element of p1

最佳答案

因为我猜你的目标是理解如何做这道题,所以我将尝试向你解释基本算法,而不是告诉你每一行的作用。

您有 2 个列表:L1 和 L2。

您基本上想用 L2 中的每个元素检查 L1 中的每个元素。 让 L1current 和 L2current 成为您正在检查的值。

您还需要一个 L2Prec,因为当您删除一个 L2 元素时,您需要将 prec 与下一个链接起来。

You start with L1current = L1 and L2current = L2;
While ( L1current is not NULL)
{
    L2current = L2; // you set the L2Current to the begging of L2 list.
    While ( L2current is not NULL) // you run untill the end.
    {
        You check if L1current == L2current;
        {
            // If they are equal
            You add the L2 element to L3;
            You connect L2prec with L2next;
            You delete L2current;
        }
        Else
        {
                L2current = L2next;
        }
    }
       L1current = L1next; // after you are done with the first element of L1 you
                          // move to the next one.
}

关于arrays - 查看两个链表是否相等的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19522985/

相关文章:

php - 在foreach循环中,有什么更好的方法……使用&符号或基于键重新分配?

c - 对数组和指针使用 sizeof 的实验

算法复杂度

python - 将遵循一个方向的一组点组合在一起的算法

Python 链表搜索

java - 从单链表扩展创建双链表 - 获取空指针

objective-c - Objective c 实现方法,它接受参数数组

c - 将字符串传递给函数。预期在 ']' 标记之前表达。使用C

php - 投注申请,获得获胜球队的赔率

c# - 在 (c#) 库中使用 List<T> 与 LinkedList<T> 的性能差异是什么