51.链表中环的入口结点

链表中环的入口结点
  • 参与人数:1833时间限制:1秒空间限制:32768K
  • 本题知识点:  链表
  •  算法知识视频讲解

题目描述

一个链表中包含环,请找出该链表的环的入口结点。
牛客网不给测试用例让人好桑心。。
// 51.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};

class Solution {
public:
	ListNode* EntryNodeOfLoop(ListNode* pHead) {
		if (pHead == NULL) return NULL;

		int length = loopLength(pHead);
		if (length == 1)return NULL;

		ListNode* p1 = pHead;
		ListNode* p2 = pHead;

		for (int i = 0; i < length; i++) {
			p2 = p2->next;
		}

		while (p1 != p2) {
			p1 = p1->next;
			p2 = p2->next;
		}

		return p1;
	}

	int loopLength(ListNode* pHead) {
		ListNode* p1 = pHead;
		ListNode* p2 = pHead->next;

		while (p1 != p2 && p2 != NULL) {
			p1 = p1->next;
			p2 = p2->next->next;
		}

		ListNode* tmp = p1->next;
		int retVal = 1;
		while (tmp != p1 && tmp != NULL) {
			tmp = tmp->next;
			++retVal;
		}

		return retVal;
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	ListNode p1(1);
	ListNode p2(2);
	ListNode p3(3);
	ListNode p4(4);
	ListNode p5(5);
	ListNode p6(6);

	p1.next = &p2;
	p2.next = &p3;
	p3.next = &p4;
	p4.next = &p5;
	p5.next = &p6;
	p6.next = &p3;

	Solution s;
	ListNode* result = s.EntryNodeOfLoop(&p1);
	return 0;
}

// 51.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};

class Solution {
public:
	ListNode* EntryNodeOfLoop(ListNode* pHead){
		if (pHead == NULL || pHead->next == NULL) return NULL;

		ListNode* p1 = pHead;
		ListNode* p2 = pHead;

		int length = 0;
		while (p2 != NULL && p2->next != NULL) {
			p1 = p1->next;
			p2 = p2->next->next;
			++length;
			if (p1 == p2) {
				break;
			}
		}

		p1 = pHead;
		p2 = pHead;
		for (int i = 0; i < length; i++) {
			p2 = p2->next;
		}

		while (p1 != p2) {
			p1 = p1->next;
			p2 = p2->next;
		}

		return p1;
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	ListNode p1(1);
	ListNode p2(2);
	ListNode p3(3);
	ListNode p4(4);
	ListNode p5(5);
	ListNode p6(6);

	p1.next = &p2;
	p2.next = &p3;
	p3.next = &p4;
	p4.next = &p5;
	p5.next = &p6;
	p6.next = &p3;

	Solution s;
	ListNode* result = s.EntryNodeOfLoop(&p1);
	return 0;
}


你可能感兴趣的:(51.链表中环的入口结点)