JZ52 两个链表的第一个公共节点

image
image
image

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
#include <endian.h>
class Solution {
public:
	//返回类型为 节点指针类型, 传入的是两个链表的头节点
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
		
		//先得到两个链表的长度,计算它俩的差x,让长的那个先走x步
		//让后一起走,如果都走到最后还没有找到相同的,则这两个链表没有相同的节点
		int length1 = GetLengethOfList(pHead1);
		int length2 = GetLengethOfList(pHead2);
		int x = 0;

		if(length1 < length2)
		{
			x = length2 - length1;
			for(int i = 0; i < x ; i++)
			{
				pHead2 = pHead2->next;
			}
		}
		else {
			x = length1 - length2;
			for(int j = 0; j < x ; j++)
			{
				pHead1 = pHead1->next;
			}
		}

		//两个链表走到相同的节点,或者两个节点都走到头
		//当链表1为空,或者链表2为空,或者是链表1的值等于链表2的值 时结束循环
		while(pHead1 && pHead2 && pHead1 != pHead2)
		{
			pHead1 = pHead1->next;
			pHead2 = pHead2->next;
		}
		return pHead2;
	
    }

	int GetLengethOfList (ListNode* pHead)
	{	
		int i = 0;
		while(pHead)
		{
			i++;
			pHead = pHead->next;
		}
		return i;
	}
};

posted @ 2024-04-12 18:42  蓝色的海嗷  阅读(42)  评论(0)    收藏  举报