leetcode 160 相交链表

简介

比较浪费空间的思路, 不如官网的好

code

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        vector<ListNode *> v1;
        vector<ListNode *> v2;
        ListNode * p = headA;
        ListNode * q = headB;
        while(p){
            v1.push_back(p);
            p=p->next;
        }
        while(q){
            v2.push_back(q);
            q=q->next;
        }
        reverse(v1.begin(), v1.end());
        reverse(v2.begin(), v2.end());
        vector<ListNode *> rlt;
        for(int i=0; i< v1.size() && i < v2.size(); i++){
            if(v1[i] == v2[i]){
                rlt.push_back(v1[i]);
            }
        }
        if(rlt.size() ){
            return rlt.back(); // 返回最后一个元素
        }
        return NULL;
    }
};
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
            return null;
        }
        ListNode p = headA;
        ListNode q = headB;
        while(p != q){
            p = p == null ? headB : p.next;
            q = q == null ? headA : q.next;
        }
        return q;
    }
}

java 使用官网的思路, https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/tu-jie-xiang-jiao-lian-biao-by-user7208t/

Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14774917.html