leetcode 160. Intersection of Two Linked Lists

题目描述:

思路:可以链表逆序找到最后一个重合的结点:借助两个栈来实现。

也可以找出两个链表的长度差值,让长的链表先走差值步,然后一起走,找到的重合点即为第一个重合的结点

/**  第二种
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int len1 = 0, len2 = 0;
        if(headA == NULL || headB == NULL)
            return NULL;
        ListNode *tmp1 = headA;
        ListNode *tmp2 = headB;
        
        while(tmp1 != NULL){
            len1++;
            tmp1 = tmp1-> next;
        }

        while(tmp2 != NULL){
            len2++; 
            tmp2 = tmp2 -> next;
        }
        tmp1 = headA;
        tmp2 = headB;
        
        if(len1 > len2){
            int a = len1-len2;
            while(a--){
                tmp1 = tmp1 ->next;
            }
        }
        else{
            int b = len2-len1;
            while(b--){
                tmp2 = tmp2 -> next;
            }
        }
        while(tmp1 != NULL && tmp2 != NULL){
            if(tmp1 == tmp2)
                return tmp1;
            tmp1 = tmp1->next;
            tmp2 = tmp2->next;
        }
        return NULL;
    }
};
/** 第一种
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        stack<ListNode *> st1;
        stack<ListNode *> st2;
        
        if(headA == NULL || headB == NULL)
            return NULL;
        while(headA != NULL){
            st1.push(headA);
            headA = headA -> next;
        }
        while(headB != NULL){
            st2.push(headB);
            headB = headB -> next;
        }
        bool flag = false;
        ListNode *last = st1.top();
        
        while(!st1.empty() && !st2.empty()){
            ListNode *tmp1 = st1.top();
            st1.pop();
            ListNode *tmp2 = st2.top();
            st2.pop();
            if(tmp1 == tmp2){
                last = tmp1;
                flag = true;
            }
            else{
                break;
            }
            
        }
        if(flag)
            return last;
        else
            return NULL;
    }
};
原文地址:https://www.cnblogs.com/strongYaYa/p/6780319.html