160. Intersection of Two Linked List
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.
这道题目咋看,反正我不知道如何下手,谈谈这段代码的思想吧,把A和B整合成一个链表,如果他们有重合的,那么就会相等,然后返回节点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *p1,*p2;
p1=headA;
p2=headB;
while((p1!=NULL||p2!=NULL)&&p1!=p2){
p1=p1?p1->next:headB;
p2=p2?p2->next:headA;
}
return p1;
}