LeetCode Day12:相交链表

发布于 2022-09-01  42 次阅读


题号:160
难度:Easy
链接:https://leetcode.cn/problems/intersection-of-two-linked-lists

思路

将两个链表中结点分别遍历入栈,再逐个弹出并对比,若结点不相同,则上一个弹出的结点为相交结点。

代码

#include <vector>

using std::vector;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        vector<ListNode*> a,b;
        ListNode* pa=headA,*pb=headB;
        while(pa!=nullptr){
            a.insert(a.end(),pa);
            pa=pa->next;
        }
        while(pb!=nullptr){
            b.insert(b.end(),pb);
            pb=pb->next;
        }
        auto ritera=a.rbegin();
        auto riterb=b.rbegin();
        ListNode* temp=nullptr;
        for(;ritera!=a.rend()&&riterb!=b.rend()&&*ritera==*riterb;++ritera,++riterb) temp=*ritera;
        return temp;
    }
};

提交结果

LeetCode-Day12:相交链表-2022-09-04-16-40-03