描述
请写一个程序,找到两个单链表最开始的交叉节点。
- 如果两个链表没有交叉,返回
null
。 - 在返回结果后,两个链表仍须保持原有的结构。
- 可假定整个链表结构中没有循环。
您在真实的面试中是否遇到过这个题? 是
样例
下列两个链表:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
在节点 c1 开始交叉。
挑战
需满足 O(n) 时间复杂度,且仅用 O(1) 内存。
题目链接
程序
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
*/
ListNode * getIntersectionNode(ListNode * headA, ListNode * headB) {
// write your code here
if(headA == NULL || headB == NULL)
return NULL;
ListNode *cur = headA;
int lenA = 0, lenB = 0;
//分别求出A和B的长度
while(cur){
++lenA;
cur = cur->next;
}
cur = headB;
while(cur){
++lenB;
cur = cur->next;
}
//让长度长的链表先走|lenA - lenB|步
if(lenA > lenB){
int tmp = lenA - lenB;
while(tmp != 0){
--tmp;
headA = headA->next;
}
}
else if(lenA < lenB){
int tmp = lenB - lenA;
while(tmp != 0){
--tmp;
headB = headB->next;
}
}
//返回相交的节点,没有则返回空
while(headA != NULL && headB != NULL){
if(headA == headB)
return headA;
headA = headA->next;
headB = headB->next;
}
return NULL;
}
};