简介

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

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/

posted on 2021-05-16 21:23  HDU李少帅  阅读(28)  评论(0编辑  收藏  举报