letecode [160] - Intersection of Two Linked Lists

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

题目大意

   给定两个链表,找到它们的第一个公共节点并返回。

理  解:

   从第一个公共节点开始,两链表后面的节点都是公共的。

  计算两个链表的长度,从长度相同的节点开始往后遍历,并比较p==q,若相等,则当前节点为第一个公共节点;不等则继续往后找。

代 码 C++:

/**
 * 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;
        int lenA=0,lenB=0;
        ListNode *p = headA;
        ListNode *q = headB;
        while(p!=NULL){
            lenA++;
             p = p->next;
        }
        while(q!=NULL){
            lenB++;
            q = q->next;
        }
        p = headA;
        q = headB;
        while(lenA>lenB){
            p = p->next;
            lenA--;
        }
        while(lenA<lenB){
            q = q->next;
            lenB--;
        }
        while(p!=NULL){
            if(p==q){
                return p;
            }
            p = p->next;
            q = q->next;
        }
        return NULL;
    }
};

运行结果:

   执行用时 :72 ms, 在所有C++提交中击败了84.85%的用户

  内存消耗 :16.9 MB, 在所有C++提交中击败了11.06%的用户
posted @ 2019-06-11 10:54  lpomeloz  阅读(310)  评论(0编辑  收藏  举报