【LeetCode 160】Intersection of Two Linked Lists

时间:2023-03-09 09:54:01
【LeetCode 160】Intersection of Two Linked Lists

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.

题意:

  给两个可能相交的链表,求出其交点位置。

思路:

  1.将其中一条链表(B)的首位相连,问题转换为“求一个带环链表(A)的入环位置”。

  2.从链表(A)起始处利用快慢指针(p1、p2)遍历环,得到快慢指针相等的结点(p1 == p2)的位置。

  3.将p1指向链表(A)的起始处后,p1、p2同步走。

  4.走至 p1 == p2 的位置处,即为所求结点。

  ps:1.要判断可能不相交的情况 2.不能改动原本的数据结构(B的尾指针在返回前要置为0)

C++:

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == || headB == )
return ; ListNode *phb = headB;
while(phb->next != )
phb = phb->next;
phb->next = headB; bool isloop = false;
ListNode *pha = headA;
while(pha != )
{
if(pha == headB)
{
isloop = true;
break;
}
pha = pha->next;
} if(!isloop)
{
phb->next = ;
return ;
} ListNode *p1 = headA->next;
ListNode *p2 = headA->next->next; while(p1 != p2)
{
p1 = p1->next;
p2 = p2->next->next;
} p1 = headA; while(p1 != p2)
{
p1 = p1->next;
p2 = p2->next;
} phb->next = ;
return p1;
}
};