我有一个算法,它比较两个链表 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