题解 | #两个链表的第一个公共结点(优化)#

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

https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
//时间复杂度O(m+n)两个指针轮流走,必定会相遇
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
		ListNode* temp1 = pHead1;
		ListNode* temp2 = pHead2;
		if(temp1==NULL||temp2==NULL){
			return NULL;
		}

		while(temp1 != temp2){
			if (temp1 ==NULL){
				temp1= pHead2;  //这已经相当于走了一步,不应该再走了
				continue;
			}
			if(temp2 ==NULL){
				temp2 = pHead1;
				continue;
			}
			temp1= temp1 ->next;
			temp2 = temp2 ->next;
			
		}
        return temp1;
    }
};

全部评论

相关推荐

06-03 15:32
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务