【数据结构·考研】链表的相交结点

题目:编写一个程序,找到两个单链表相交的起始结点(相交后链表合二为一)。
解析:假设链表LA不相交部分长度为a,LB不相交部分长度为b,相交部分长度为c。如果链表A与链表B的长度不等,且相交,则指针pA会遍历完链表LA,指针pB会遍历完链表LB,两个指针不会同时到达链表的尾节点,然后指针pA移到链表LB的头节点,指针pB移到链表headA的头节点,然后两个指针继续移动,在指针pA移动了a+c+b次、指针pB移动了b+c+a次之后,两个指针会同时到达两个链表相交的节点,该节点也是两个指针第一次同时指向的节点,此时返回相交的节点。 

示例:
    LA→0→0→0→0→0↘
                                       0→0→0→null 
             LB→0→0→0↗     

解题思路:快慢指针

/*
双指针
*/
ListNode* getIntersectionNode(LinkList& LA, LinkList& LB) {
    if (LA == NULL || LB == NULL) return NULL; //空链表返回 
    ListNode *pA = LA, *pB = LB;
    while (pA != pB) { //pA不等于pB 
        pA = pA == NULL ? LB : pA->next;
        pB = pB == NULL ? LA : pB->next;
    }
    return pA;
}

完整代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

typedef struct node{
	int val;
	struct node* next;
}ListNode,*LinkList; 

//双指针 
ListNode* getIntersectionNode(LinkList& LA, LinkList& LB) {
    if (LA == NULL || LB == NULL) return NULL; //空链表返回 
    ListNode *pA = LA, *pB = LB;
    while (pA != pB) { //pA不等于pB 
        pA = pA == NULL ? LB : pA->next;
        pB = pB == NULL ? LA : pB->next;
    }
    return pA;
}

//尾插法 
ListNode* createListR(int finish){ //约定以finish结束 
	int x;
	cin >> x;
	if(x == finish) return NULL; //递归边界 
	ListNode* p = new ListNode;
	p->val = x;
	p->next = createListR(finish); //把剩余的创建任务交给下一层 
	return p;	
}
 
void printList(ListNode* p){
	if(p == NULL) return;
	cout<<p->val<<" ";
	printList(p->next);
} 
 
int main(){
	ListNode* p = createListR(9999); //1 2 3 4 5 6 7 8 9 9999 
	ListNode* q = createListR(9999); //1 2 3 4 5 9999
	ListNode* k = getIntersectionNode(p, q);
	if(k == NULL) cout<<"不相交"<<endl;
	else cout<<"相交于结点"<<k->val<<endl; 
	for(k = q; k->next != NULL; k = k->next);
	k->next = p->next->next->next;
	k = getIntersectionNode(p, q);
	if(k == NULL) cout<<"不相交"<<endl;
	else cout<<"相交于结点"<<k->val<<endl; 
}

结果如下:

 更多代码请参考:手撕考研数据结构(代码汇总)

猜你喜欢

转载自blog.csdn.net/cjw838982809/article/details/130992527