这是链接列表代码,那么如何制作两个不同的列表并显示它们之间的交集? 例如,有两个名为L1和L2的链表,那么如何实现一个显示这两个列表交集的函数,如L1有1,2,3,4,5和L2有11,3,4 所以结果将是3,4。
#include <iostream>
using namespace std;
#include "Node.h"
class DoublyLinkedList{
private:
Node* head;
Node* tail;
Node* list;
int elementCount;
public:
DoublyLinkedList(){
head = tail = list = NULL;
elementCount = 0;
}
void insertAtFront(int item){
elementCount++;
Node* newNode;
newNode = new Node;
newNode->data = item;
list = head;
if(list == NULL) {
head = newNode;
tail = head;
return;
}
newNode->next = head;
head->prev = newNode;
head = newNode;
head->prev = tail;
tail->next = head;
}
void insertAtEnd(int item){
elementCount++;
Node* newNode;
newNode = new Node;
newNode->data = item;
list = head;
if(list == NULL){
head = newNode;
tail = head;
return;
}
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
head->prev = tail;
tail->next = head;
}
bool insertAtIndex(int item, int index){
if(index > elementCount){
cout << "Invalid index" << endl;
return false;
}
else if(index == 0){
insertAtFront(item);
}
else if(index == elementCount){
insertAtEnd(item);
}
else {
Node* newNode = new Node;
newNode->data = item;
list = getNodeAt(index - 1);
newNode->next = list->next;
list->next->prev = newNode;
list->next = newNode;
newNode->prev = list;
elementCount++;
}
return true;
}
};
答案 0 :(得分:3)
由于这是一项学习任务,以下是该方法的一般描述:
bool contains(int value) const
,它接受int value
并在列表包含指定值时返回true
;这个函数会有一个循环。DoublyLinkedList intersectWith(DoublyLinkedList& other) const
:DoublyLinkedList result
other.contains(node.data)
true
,请检查result.contains(node.data)
是否返回false
以消除重复other.contains(node.data) && !result.contains(node.data)
,请将node.data
添加到result
result
列表。