[LeetCode160]Intersection of Two Linked Lists

时间:2023-03-08 23:08:13
[LeetCode160]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.

 

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.

思路:求一个单链表交集的首结点

  方法一:找出两个链表的长度差n,长链表先走n步,然后同时移动,判断有没有相同结点

  方法二:两个链表同时移动,链表到尾部后,跳到链表头部,相遇点即为所求

代码:

方法一:

 /**
* 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) {
//方法一
ListNode *p = headA;
ListNode *q = headB;
if(!p || !q) return NULL;
while(p && q && p != q)
{
p = p->next;
q = q->next;
if(p == q)
return p;
if(!p)
p = headB;
if(!q)
q = headA;
}
return p;
}
};

方法二:

 /**
* 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 == NULL || headB == NULL) return NULL;
ListNode *p = headA;
ListNode *q = headB;
int countA = , countB = ;
while (p->next)
{
p = p->next;
++countA;
}
while (q->next)
{
q = q->next;
++countB;
}
if (p != q) return NULL;
if (countA > countB)
{
for (int i = ; i < countA - countB; ++i)
headA = headA->next;
}
else if (countB > countA)
{
for (int i = ; i < countB - countA; ++i)
headB = headB->next;
}
while (headA != headB)
{
headA = headA->next;
headB = headB->next;
}
return headA; }
};