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

原文地址:https://www.jianshu.com/p/0434efbfbdad

时间限制:1秒 空间限制:32768K

题目描述

输入两个链表,找出它们的第一个公共结点。

我的代码

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        int len1=ListLen(pHead1);
        int len2=ListLen(pHead2);
        if(len1<len2)
            pHead2=WalkSteps(pHead2,len2-len1);
        if(len1>len2)
            pHead1=WalkSteps(pHead1,len1-len2);
        while(pHead1){
            if(pHead1==pHead2)
                return pHead1;
            pHead1=pHead1->next;
            pHead2=pHead2->next;
        }
        return nullptr;
    }
    int ListLen(ListNode* p){
        int len=0;
        while(p){
            len++;
            p=p->next;
        } 
        return len;
    }
    ListNode* WalkSteps(ListNode *p,int steps){
        while(steps){
            p=p->next;
            steps--;
        }
        return p;
    }
};

运行时间:3ms
占用内存:504k

原文地址:https://www.cnblogs.com/cherrychenlee/p/10822293.html