正如問題的名稱所示。我需要採取2個鏈表,並創建第三個列表中的前兩個鏈接列表通用的元素。創建LinkedListC中的鏈接列表A和B共有的元素C++
這裏是我寫
void computeC(DLL<int> &a, DLL<int> &b, DLL<int> &c)
{
Node<int> *hunterA, *hunterB;
hunterA = a.getHead();
hunterB = b.getHead();
while (hunterA != NULL)
{
while (hunterB != NULL)
{
int aData = hunterA->data, bData = hunterB->data;
if (aData == bData)
{
int temp = bData;
c.progAppend2(temp);
}
else
{
hunterB = hunterB->next;
}
}
hunterA = hunterA->next;
}
c.output();
}
這裏是我的雙向鏈表類
template <class Type>
void DLL<Type>::progAppend2(Type data)
{
Node<Type> *newNode = new Node<Type>;
newNode->data = data;
if (head == NULL)
{
head = newNode;
tail = newNode;
size++;
}
else
{
tail->next = newNode;
newNode->prev = tail;
tail = tail->next;
size++;
}
}
的progAppend2()函數的函數,這裏是主要的()
int main (void)
{
int a[9] = {3,7,10,15,16,9,22,17,32};
int b[9] = {16,2,9,13,37,8,10,1,28};
DLL<int> listA, listB, listC, listD;
for (int i = 0; i < 9; i++)
{
listA.progAppend2(a[i]);
listB.progAppend2(b[i]);
}
computeC(listA,listB,listC);
listC.output();
return 0;
}
我遇到的問題是由於某種原因,ListC沒有被填充任何東西,只是輸出和空的lis當我調用output();
我認爲問題在於computeC函數。 outer while循環應該設置hunterA指向ListA中的一個元素,然後內部循環應該將listB的每個元素與hunterA指向的元素進行比較。如果找到匹配項,那麼該元素將被複制到ListC中。在這種情況下,我認爲它應該工作。我真的很感激任何幫助。
的可能重複[鏈表路口(http://stackoverflow.com/questions/8919442/linked-list-intersection) – 2013-05-08 20:28:53