美文网首页
LintCode 380. Intersection of Tw

LintCode 380. Intersection of Tw

作者: aammyytt | 来源:发表于2018-04-15 15:27 被阅读0次

    題目:
    Write a program to find the node at which the intersection of two singly linked lists begins.

    Notice
    If the two linked lists have no intersection at all, return null.
    The linked lists must retain their original structure after the function returns.
    You may assume there are no cycles anywhere in the entire linked structure.

    思路:

    1. 先找出哪一條比較常,然後把 head長移動位置,讓兩條 linked list 出發點相同

    代碼:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    
    
    class Solution {
    public:
        /*
         * @param headA: the first list
         * @param headB: the second list
         * @return: a ListNode
         */
        ListNode * getIntersectionNode(ListNode * headA, ListNode * headB) {
            // write your code here
            if (headA == NULL || headB == NULL)
                return NULL;
            
            int lenA = 0;
            int lenB = 0;
            ListNode* nodeA = headA;
            ListNode* nodeB = headB;
            
            while(nodeA!=NULL){
                lenA++;
                nodeA = nodeA->next;
            }
            
            while(nodeB!=NULL){
                lenB++;
                nodeB = nodeB->next;
            }
                
            int N = abs(lenB-lenA);
            
            if(lenB > lenA) {
                for(int i = 0; i < N; i++){
                    headB = headB->next;
                }
            }
            else if(lenA > lenB){
                for(int i = 0; i < N; i++){
                    headA = headA->next;
                }
            }
            
            while(headA != headB){
                headA = headA->next;
                headB = headB->next;
            }
            
            return headA;
        }
    };
    

    相关文章

      网友评论

          本文标题:LintCode 380. Intersection of Tw

          本文链接:https://www.haomeiwen.com/subject/nfbdkftx.html