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

两个链表的第一个公共结点
  • 参与人数:2623时间限制:1秒空间限制:32768K
  • 本题知识点:  链表
  •  算法知识视频讲解

题目描述

输入两个链表,找出它们的第一个公共结点。
最喜欢做链表的题了,舒爽~
// 31.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
	ListNode* FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2) {
		if (pHead1 == NULL || pHead2 == NULL) return NULL;

		int length1 = 0;
		ListNode* pNode1 = pHead1;
		while (pNode1 != NULL) {
			pNode1 = pNode1->next;
			length1++;
		}

		int length2 = 0;
		ListNode* pNode2 = pHead2;
		while (pNode2 != NULL) {
			pNode2 = pNode2->next;
			length2++;
		}

		int cur = length2;
		pNode1 = pHead1;
		pNode2 = pHead2;
		if (length1 > length2) {
			int n = length1 - length2;
			for (int i = 0; i < n; i++) {
				pNode1 = pNode1->next;
			}
			cur = length2;
		}
		else if (length2 > length1) {
			int n = length2 - length1;
			for (int i = 0; i < n; i++) {
				pNode2 = pNode2->next;
			}
			cur = length1;
		}

		ListNode* retVal = NULL;
		for (int i = 0; i < cur; i++) {
			if (pNode1 == pNode2) {
				retVal = pNode1;
				break;
			}
			pNode1 = pNode1->next;
			pNode2 = pNode2->next;
		}
		return retVal;
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	ListNode p1(1);
	ListNode p2(2);
	ListNode p3(3);
	p1.next = &p2;
	p2.next = &p3;

	ListNode p4(4);
	ListNode p5(5);
	p4.next = &p5;

	ListNode p6(6);
	ListNode p7(7);
	p6.next = &p7;

	p3.next = &p6;
	p5.next = &p6;

	Solution s;
	ListNode* result = s.FindFirstCommonNode(&p1, &p4);
	return 0;
}

你可能感兴趣的:(33.两个链表的第一个公共结点)