一个双向链表+Vector查找

题目是有一堆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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值