判断两链表相交的问题(分有环和无环,以及求第一个相交结点)

来源:互联网 发布:阿里云打印域名证书 编辑:程序博客网 时间:2024/06/07 19:17
首先用一个函数判断两个链表是否有环
  1.如果两个链表都没有环,则判断最后一个结点是否相等,如果相等,则相交,如果不等,则不想交
  2.如果只有一个有环,则不相交
  3.如果两个都有环,则看其中一个环里的点在另一个环里是否出现,如果出现则相交,否则不相交


//判断是否有环,如果有返回true和环中结点,无返回false和最后一个结点

typedef ElemType int;typedef struct Node{ElemType data;struct Node *next;}Node,*pNode;bool isCircled(pNode head,pNode &circleNode,pNode &lastNode){pNode first=head;pNode second=head->next;while(!first&&!second&&first!=second){if(second->next!=NULL)second=second->next;if(first->next==NULL)lastNode=first;if(second->next!=NULL)lastNode=second;first=first->next;second=second->next;}if(!first&&!second&&first==second){circleNode=first;return true;}return false;}//判断是否相交bool isCrossed(pNode head1,pNode head2){pNode circleNode1,circleNode2;pNode lastNode1,lastNode2;bool state1=isCircled(head1,circleNode1,lastNode1);bool state2=isCircled(head2,circleNode2,lastNode2);//1.如果两链表都无环,则判断最后一个结点是否相等,如果相等,则相交if(state1||state2){if(lastNode1==lastNode2)return true;else return false;}//2.只有一个有环,则不相交else if(!(state1&&state2)){return false;}//3.都有环,则判断第一个环内的点是否在第二个环内出现,如果出现则相交,否则不相交else{pNode tmp=circleNode1->next;while(tmp!=circleNode1){if(tmp==circleNode1)return true;tmp=tmp->next;}return false;}return false;}

//求链表相交的第一个结点思路:求出两量表长度之差,让长链表遍历插值个结点,然后再同步遍历两个链表,直到有相同结点

0 0
原创粉丝点击