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/

上一篇:160个creakme(一


下一篇:leetcode之链表一: 160-相交链表