LeetCode160. 相交链表

编写一个程序,找到两个单链表相交的起始节点。

例如,下面的两个链表

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

在节点 c1 开始相交。

题目分析:首先求出链表A和链表B的长度,然后看长链表比短链表长几格,那么长链表的头结点就往后走几格,最后两个链表一起开始往后走,相遇的第一个节点就是起始节点。如果两个链表不相交的话,那么相遇的第一个节点必然是空节点。

代码展示:
 

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int lenA = 0,lenB = 0;
        ListNode *tempA = headA;
        ListNode *tempB = headB;
        while(tempA!=NULL){
            tempA = tempA->next;
            lenA += 1;
        }
        while(tempB!=NULL){
            tempB = tempB->next;
            lenB += 1;
        }
        tempA = headA;
        tempB = headB;
        while(lenA>lenB){
            tempA = tempA->next;
            lenA -= 1;
        }
        while(lenB>lenA){
            tempB = tempB->next;
            lenB -= 1;
        }
        while(tempA!=tempB){
            tempA = tempA->next;
            tempB = tempB->next;
        }
        return tempA;
    }
};

猜你喜欢

转载自blog.csdn.net/Jaster_wisdom/article/details/81408128