(LeetCode 160)Intersection of Two Linked Lists

时间:2024-12-09 22:33:38

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.

题目要求:

求两个链表的交点,如果没有,则返回NULL

要求O(n)的时间复杂度和O(1)的空间复杂度

解题思路:

1、如果不考虑空间复杂度,可以用set容器记录第一个链表的所有结点,依次遍历第二个链表,第一个存在set中的结点即为交点,否则不存在。

2、第一个链表长为x,第二个链表长为y,假设x>y,让第一个链表指针先走x-y步,(这样两个链表指针就长度对齐),然后两个链表指针一起走,如果遇到对应相等,则为交点,否则不存在。

代码:

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int getLength(ListNode *head){
int i=;
for(ListNode *p=head;p!=NULL;p=p->next)
i++;
return i;
} ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==NULL || headB==NULL) return NULL;
int lenA=,lenB=;
ListNode *pA,*pB;
pA=headA;
pB=headB; lenA=getLength(pA);
lenB=getLength(pB); if(lenA>lenB){
for(int i=lenA-lenB;i>;i--)
pA=pA->next;
} if(lenB>lenA){
for(int i=lenB-lenA;i>;i--)
pB=pB->next;
} while(pA!=pB){
pA=pA->next;
pB=pB->next;
} if(pA==pB)
return pA;
else
return NULL;
}
};