LintCode-380.两个链表的交叉

时间:2024-05-01 03:30:18

两个链表的交叉

请写一个程序,找到两个单链表最开始的交叉节点。

注意事项

  • 如果两个链表没有交叉,返回null。
  • 在返回结果后,两个链表仍须保持原有的结构。
  • 可假定整个链表结构中没有循环。

样例

下列两个链表:

LintCode-380.两个链表的交叉

在节点 c1 开始交叉。

挑战

需满足 O(n) 时间复杂度,且仅用 O(1) 内存。

标签

链表

code

/**
* 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
stack<ListNode *> stackA, stackB;
ListNode * result=NULL,*pA=headA,*pB=headB; if(headA==NULL || headB==NULL)
return result; while(pA != NULL) {
stackA.push(pA);
pA = pA->next;
}
while(pB != NULL) {
stackB.push(pB);
pB = pB->next;
} while(!stackA.empty() && !stackB.empty()) {
if(stackA.top() == stackB.top()) {
result = stackA.top();
stackA.pop();
stackB.pop();
}
else {
break;
}
}
return result;
}
};