leetcode面试题02 07

一定要注意⚠️ 如果是要到标号为2的链表,那么需要从虚拟节点bubble开始,若n=2

则while(n--)bubble = bubble->next可以正好到n=2标记的链表处

关于leetcode19和leetcode力扣的纠结

力扣

这道题 最后判断相等的条件是指针相等,不是->val相等

class Solution {

public:

ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {

ListNode* b1 = headA;

ListNode* b2 = headB;

int lena=0;

int lenb=0;

while(b1)

{

lena++;

b1 = b1->next;

}

while(b2)

{

lenb++;

b2 = b2->next;

}

b1 = headA;

b2 = headB;

if(lenb>lena)

{

swap(lena,lenb);

swap(b1,b2);

//lena long

}

int gap = lena-lenb;

while(gap--)

{

b1 = b1->next;

}

while(b1)

{

if(b1 == b2)

return b1;

b1 = b1->next;

b2 = b2->next;

}

return NULL;




 

}

};

你可能感兴趣的:(算法,数据结构,c++)