两个链表的交叉

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

思路:遍历两个链表到最后,判断连个链表最后的位置是否相同,不同直接返回;用两个变量记录链表的长度,哪个长 先往后遍历到一样长,接着另一个也开始同时遍历,直到相等,返回头指针

代码:

/**
* 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
ListNode* tmpb = headB;
ListNode* tmpa = headA;
while (tmpa!=NULL){
tmpb = headB;
while (tmpb!=NULL){
if (tmpa->val!=tmpb->val){
tmpb = tmpb->next;;
}
else{
return tmpa;
}
}
tmpa = tmpa->next;
}
return NULL;
}
};

截图:

原文地址:https://www.cnblogs.com/w1500802028/p/7296507.html