你能帮我解决这个问题吗?我试图找到两个链表的交集。清单1包含42,32,54,58,96,17。清单2包含17,31,42,32,3,13。这是我的数据结构类。我只需要一个提示。到目前为止,我已经尝试编写FOR循环。我被告知要以类似的方式将其写入作业中的另一个循环,但它不起作用。它不是给出32,42,17的交叉输出,而是给我一个列表数字的组合。
template <class Type>
void listDifference(linkedListType<Type>& difference,
linkedListType<Type>& list1,
linkedListType<Type>& list2)
{
linkedListIterator<int> itr1;
linkedListIterator<int> itr2;
for (itr1 = list1.begin(); itr1 != list1.end(); ++itr1)
{
// Add the each element in list 1 to the difference list
difference.insertLast(*itr1);
for (itr2 = list2.begin(); itr2 != list2.end(); ++itr2)
{
if (*itr1 == *itr2)
{
// If the node is in both lists delete the node from the
// difference list.
difference.deleteNode(*itr1);
}
}
}
}
template <class Type>
void listIntersection(linkedListType<Type>& intersection,
linkedListType<Type>& list1,
linkedListType<Type>& list2)
{
linkedListIterator<int> itr1;
linkedListIterator<int> itr2;
for (itr1 = list1.begin(); itr1 != list1.end(); ++itr1)
{
intersection.insertLast(*itr1);
//add each element of list 1 to the insertion list
for (itr2 = list2.begin(); itr2 != list2.end(); ++itr2)
{
if (*itr1!=*itr2)
{// if node in list 1 is not the same as in list 2 delete the node
intersection.deleteNode (*itr1);
}
}
}
}
答案 0 :(得分:1)
我不知道为什么你要添加一个元素只是为了删除它,如果它不应该在那里。只有当应该在那里时,你才能更好地添加元素。
伪代码将是:
def intersect (list A, list B):
create empty list result
for each elementA in list A:
for each elementB in list B:
if elementA == elementB:
add elementA to list result
break
return result
您的C代码的具体问题是,对于列表B中任何元素与列表A中的当前元素不匹配,您将其从交叉点中删除:
if (*itr1 != *itr2) {
intersection.deleteNode (*itr1);
}
因此,除非列表B中的每个元素与列表A中的元素匹配,否则它将被删除。如果您将上述伪代码翻译成您的情况,您应该会取得更多成功。
而且,由于我的伪代码非常接近Python,我们可以测试它:
def intersect (A, B):
result = []
for elementA in A:
for elementB in B:
if elementA == elementB:
result.append (elementA)
break
return result
print intersect ([42,32,54,58,96,17], [17,31,42,32,3,13]);
并且正如预期的那样输出:
[42, 32, 17]
答案 1 :(得分:0)
我希望这就是你想要的。
for (itr1 = list1.begin(); itr1 != list1.end(); ++itr1)
{
for (itr2 = list2.begin(); itr2 != list2.end(); ++itr2)
{
if (*itr1==*itr2)
{
intersection.insertLast(*itr1);
}
}
}