单链表中环的入口

在这里插入图片描述
以上的证明是fast和slow刚开始都是指向头结点

public static Node EntryOfLoop(Node head) {
		if(head==null||head.next==null||head.next.next==null)
			return null;
		Node fast=head.next.next;
		Node slow=head.next;
		//或者把上两语句改成如下注释的
		//Node fast=head;
		//Node slow=head;
		//if(fast.next==null||fast.next.next==null)
			//return null;
		//slow=slow.next;
		//fast=fast.next.next;
		while(fast!=slow)
		{
			if(fast.next==null||fast.next.next==null)
				return null;
			slow=slow.next;
			fast=fast.next.next;
		}
		fast=head;
		while(slow!=fast)
		{
			slow=slow.next;
			fast=fast.next;
		}
		return fast;
		
		
	}
	public static void main(String[] args) {
		Node head1 = new Node(1);
		head1.next = new Node(2);
		head1.next.next = new Node(3);
		head1.next.next.next = new Node(4);
		head1.next.next.next.next = new Node(5);
		head1.next.next.next.next.next = new Node(6);
		head1.next.next.next.next.next.next = new Node(7);
		head1.next.next.next.next.next.next = head1.next.next.next; 
		System.out.println(EntryOfLoop(head1).value);

	}

猜你喜欢

转载自blog.csdn.net/qq_42403295/article/details/88695242