题目是有一堆DoubleLinkedList,然后有一个vector记录了其中的一些节点(可能是中间的某个节点),找出vector中包含的独立DoubleLinkedList的个数。
思想是利用了双链表的性质可以前后查找。因此在Vector中前后走动找到head或者tail为止时间复杂度为O(NLOGN)
代码如下:
#include <iostream>
#include <vector>
using namespace std;
struct Node
{
int index;
Node *parent;
Node *child;
};
void createLink(Node *head1,vector<Node*> &testVector)
{
int no1;
Node *tmp;
cout<<"enter the no of nodes in Link:\n";
cin>>no1;
for(int i = 0;i<no1;++i)
{
tmp = new Node;
cout<<"input the name of "<<i+1<<" of link1"<<endl;
cin>>tmp->index;
tmp->child = head1->child;
tmp->parent = head1;
head1->child->parent = tmp;
head1->child = tmp;
if(i%2 == 0)
{
testVector.push_back(tmp);
}
}
}
//对vector元素查找,每个元素同时找parent和child直到NULL 然后和head tail对比即可。
int searchVector(Node *head,Node *tail,vector<Node *> destVec)
{
int count = 0;
Node *par,*chi;
for(size_t i = 0;i<destVec.size();++i)
{
par=destVec[i];
chi=destVec[i];
while(par->parent != NULL && chi->child != NULL)
{
par=par->parent;
chi=chi->child;
}
if(par->parent == NULL)
{
if(par == head)
count++;
}
else if(chi->child == NULL)
{
if(chi == tail)
count++;
}
}
return count;
}
int main()
{
Node *head, *tail;
head = new Node;
head->index = -1;
head->parent = NULL;
head->child = NULL;
tail=new Node;
tail->index = -1;
tail->parent = head;
tail->child = NULL;
head->child = tail;
vector<Node *> nodeV;
createLink(head,nodeV);
cout<<searchVector(head,tail,nodeV)<<endl;
return 0;
}