原题:
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
这个题目其实有些歧义的,因为这个判断的点不在于address,而是node。这相当于当作两个链表来做而不是真正意义上的交叉。
很简单,因为地址不一样。。。
但是这个东西的算法还是很巧妙,很不幸的是,我本来想用val做路标的,就算不行,实际上自己应用的时候是可以设计数据结构做路标就好。
但是这个不行。。。
所以看了答案,答案比较巧妙。
就是一个从a出发,一个从b出发,遇到NULL就换另一个链表头。原理是两个链表叠加,到达交叉点的时间一定是一样的。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode* pA;
struct ListNode* pB;
pA=headA;
pB=headB;
if(pA==NULL||pB==NULL)
return NULL;
while(true)
{
if(pA==NULL&&pB==NULL)
return NULL;
if(pA==NULL)
{
pA=headB;
}
if(pB==NULL)
{
pB=headA;
}
if(pA->val==pB->val)
{
break;
}
pA=pA->next;
pB=pB->next;
}
return pA;
}
如果是真正的链表,我觉得做一次路标更省事。。。