【题目】
编写一个程序,找到两个单链表相交的起始节点。如下面的两个链表:

在节点 c1 开始相交。
来源:leetcode
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
【示例1】

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
【示例2】

输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Reference of the node with value = 2
【提示】
如果两个链表没有交点,返回 null
在返回结果后,两个链表仍须保持原有的结构
可假定整个链表结构中没有循环
【代码】
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int callen(ListNode* listnode){
int cnt=0;
while(listnode){
listnode=listnode->next;
cnt++;
}
return cnt;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *shortlist=headA,*longlist=headB,*listnode;
if(!headA||!headB)
return NULL;
int lenA=callen(shortlist),lenB=callen(longlist);
int diff=lenB-lenA;
if(lenA>lenB){
swap(shortlist,longlist);
diff=abs(diff);
}
while(diff--){
longlist=longlist->next;
}
while(shortlist){
if(shortlist==longlist&&shortlist->next==longlist->next)
break;
shortlist=shortlist->next;
longlist=longlist->next;
}
return shortlist;
}
};

本文介绍了一种算法,用于找出两个单链表的第一个公共节点,通过比较链表长度并同步遍历来实现,确保了原有链表结构不变。
695

被折叠的 条评论
为什么被折叠?



