struct int_List_Node{
int value;
struct int_List_Node *next;
};
//判断两个无环链表是否相交
bool is_crossed( struct int_List_Node * head1 , struct int_List_Node * head2 ) {
if( ( head1 == NULL ) || ( head2 == NULL ) ) {
printf( "error,empty pointer found\n");
}
struct int_List_Node * p , * q;
p = head1;
q = head2;
while( p -> next != NULL ) {
p = p -> next;
}
while( q -> next != NULL ) {
q = q -> next;
}
if( p == q ){
return true;
}
return false;
}
//如果相交,求出第一个交点
struct int_List_Node * get_first_cross_point( struct int_List_Node * head1 , struct int_List_Node * head2 ){
struct int_List_Node * p , * q;
p = head1;
q = head2;
while( ( p != NULL ) && ( q != NULL ) ) {
p = p -> next;
q = q -> next;
}
//当p指空,q非空的时候,让p指向head2,同步后指。这样q指空的时候,p向第一个公共节点
if( p == NULL ) {
p = head2;
while( ( q != NULL ) ) {
p = p -> next;
q = q -> next;
}
return p -> next;
}
else if( q == NULL ) {
q = head1;
while( ( q != NULL ) ) {
p = p -> next;
q = q -> next;
}
return q -> next;
}
}
//判断链表是否有环
bool is_cycled( struct int_List_Node * head ) {
if( head == NULL ) {
printf( "串是空的哦~\n");
return false;
}
struct int_List_Node *p , *q;
p = q = head;
//p每次前移两个,q每次前移一个
while( 1 ) {
//注意这个条件先后,要先判断q是否为空,如果为空,则是不存在q -> next的
if( ( q == NULL ) || ( q -> next == NULL ) ) {
//这里不用判断p是否指空,因为q已经走过在p之前
return false;
}
if( ( q == p ) || ( p -> next == q ) ) {
//有环
return false;
}
else {
p = p -> next;
q = q -> next -> next;
}
}
}
//有环链表和无环链表是不会相交的
//有环链表如何求第一个交点,还不知道怎么做
链表相交、有环无环、交点等
最新推荐文章于 2023-08-31 14:18:10 发布