zoukankan      html  css  js  c++  java
  • 剑指offer | 两个链表的第一个公共节点 | 16


    思路分析

    这个题目只有两种情况,如下图

    cpp

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *findFirstCommonNode(ListNode *headA, ListNode *headB) {
            auto p=headA,q=headB;
            while(p!=q){
                p= p ? p->next : headB;
                q= q ? q->next : headA;
            }
            return q;
        }
    };
    

    python

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
            p = headA
            q = headB
            while p!=q: # 最后一定会相等
                p = p.next if p else headB
                q = q.next if q else headA
            return q
    
  • 相关阅读:
    Top WAF
    Access-Control-Allow-Origin与跨域
    SQLlite
    SHell命令总结
    yum仅下载RPM包不安装
    Taglib
    JFinal
    Eclipse maven git
    maven jetty plugin
    wechat
  • 原文地址:https://www.cnblogs.com/Rowry/p/14305377.html
Copyright © 2011-2022 走看看