题解 | #两个链表的第一个公共结点#基于栈

两个链表的第一个公共结点

https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
  public:
    stack<ListNode*> getstack(ListNode* head) {
        stack<ListNode*> s;
        while (head) {
            s.push(head);
            head = head->next;
        }
        return s;
    }
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        stack<ListNode*>s1 = getstack(pHead1);
        stack<ListNode*>s2 = getstack(pHead2);
        ListNode* node = new ListNode(0);
        while (!s1.empty() && !s2.empty()) {
            ListNode* node1 = s1.top();
            ListNode* node2 = s2.top();
            if (node1->val == node2->val) {
                node1->next = node->next;
                node->next = node1; //这里node1也可以替换为node2
                s1.pop();
                s2.pop();
            } else {
                break;
            }
        }
        return node->next;
    }
};

全部评论

相关推荐

牛可乐121381:卖课的
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务