链表假设是单链表,
这题需要找到相交的特征,相交后,最后一个节点肯定相同,所以,如果相同则是相交,否则不相交。
下面看看实现:
#include<iostream> using namespace std; struct LNode{ LNode(int _d = 0):data(_d),next(NULL) {} int data; LNode* next; }; bool findInsecNode(LNode* l1, LNode* l2) { if(l1 == NULL) return false; if(l2 == NULL) return false; LNode* pl1 = l1; LNode* pl2 = l2; while(pl1->next != NULL) pl1 = pl1->next; while(pl2->next != NULL) pl2 = pl2->next; if(pl1 == pl2) return true; else return false; } int main() { LNode* L1 = NULL; LNode* L2 = NULL; LNode n1(1); LNode n2(2); LNode n3(3); LNode n4(4); LNode n5(5); LNode n6(6); L1 = &n1; L2 = &n2; L1->next = &n3; L2->next = &n4; L1->next->next = &n5; L2->next->next = &n5; L1->next->next->next = &n6; L2->next->next->next = &n6; if(findInsecNode(L1, L2)) cout << "L1, L2 list is insection" << endl; else cout << "L1, L2 list is not insection" << endl; return 0; }
6. 微软面试题:判断俩个链表是否相交,布布扣,bubuko.com
原文:http://blog.csdn.net/hhh3h/article/details/20740031