<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">Write a program to find the node at which the intersection of two singly linked lists begins.</span>
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.
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *pA = headA;
ListNode *pB = headB;
int n= 0;
while(pA && pB)
{
pA = pA->next;
pB = pB->next;
}
if(NULL == pA && NULL == pB)
{
pA = headA;
pB = headB;
}
else if(pA)
{
while(pA)
{
pA = pA->next;
n++;
}
pA = headA;
pB = headB;
while(n)
{
pA = pA->next;
n--;
}
}
else if(pB)
{
while(pB)
{
pB = pB->next;
n++;
}
pA = headA;
pB = headB;
while(n)
{
pB= pB->next;
n--;
}
}
while(pA&&pB)
{
if(pA == pB) return pA;
pA = pA->next;
pB = pB->next;
}
return NULL;
}
};
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null)
return null;
int countA = 0;
ListNode pa = headA;
while (pa != null){
pa = pa.next;
countA++;
}
int countB = 0;
ListNode pb = headB;
while (pb != null){
pb = pb.next;
countB++;
}
pa = headA;
pb = headB;
if (countA > countB){
for (int i=0; i<countA-countB; i++){
pa = pa.next;
}
}else if (countB > countA){
for (int i=0; i<countB-countA; i++){
pb = pb.next;
}
}
while (pa != pb && pa != null){
pa = pa.next;
pb = pb.next;
}
return pa;
}
}
还有个好玩的方法就是计算listA和listB的各个节点val之和,然后让listA的每个节点val+1,然后计算listB的和,listB的和如果没有增加就没有交叉节点,交叉节点就是A的倒数第差值个节点。最后把listA的值还原。
I don't think this is a optimal solution because 1. you changed the value of input. The problem only asked to not to change data structure, but I don't think changing the value is a good idea too. 2. what if the value is not integer? like a string? If a linked list algorithm only works if all value are integer, this is not a really useful algorithm. 3. the algorithm is actually similar to the method "record every item of A in list, check which one of B is in list", just you added integer together so it didn't take O(n) space, but it really depend on the trick of integer.