160 相交链表

160 相交链表

 

 

 

 

 

160 相交链表

 

 

 

指针 pA 指向 A 链表,指针 pB 指向 B 链表,依次往后遍历
如果 pA 到了末尾,则 pA = headB 继续遍历
如果 pB 到了末尾,则 pB = headA 继续遍历
比较长的链表指针指向较短链表head时,长度差就消除了
如此,只需要将最短链表遍历两次即可找到位置

作者:reals
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/tu-jie-xiang-jiao-lian-biao-by-user7208t/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            if(headA==NULL || headB==NULL)
            {
                return NULL;
            }
            ListNode* a=headA;
            ListNode* b=headB;
            while(a!=b)
            {
                a= a==NULL?headB:a->next;
                b= b==NULL?headA:b->next;
            }
            return a;

    }
};

 

TRANSLATE with x English
Arabic Hebrew Polish
Bulgarian Hindi Portuguese
Catalan Hmong Daw Romanian
Chinese Simplified Hungarian Russian
Chinese Traditional Indonesian Slovak
Czech Italian Slovenian
Danish Japanese Spanish
Dutch Klingon Swedish
English Korean Thai
Estonian Latvian Turkish
Finnish Lithuanian Ukrainian
French Malay Urdu
German Maltese Vietnamese
Greek Norwegian Welsh
Haitian Creole Persian  
160 相交链表 160 相交链表 160 相交链表 160 相交链表   TRANSLATE with 160 相交链表 COPY THE URL BELOW 160 相交链表 160 相交链表 Back EMBED THE SNIPPET BELOW IN YOUR SITE 160 相交链表 Enable collaborative features and customize widget: Bing Webmaster Portal Back
上一篇:dpwwn:2 Vulnhub Walkthrough


下一篇:MinU: v2 Vulnhub Walkthrough