首页 > 其他 > 详细

LeetCode_141. Linked List Cycle

时间:2019-10-13 09:50:31      阅读:91      评论:0      收藏:0      [点我收藏+]

 

141. Linked List Cycle

Easy

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

 

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

技术分享图片

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

技术分享图片

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

技术分享图片

 

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

 

package leetcode.easy;

import java.util.HashSet;
import java.util.Set;

public class LinkedListCycle {
	@org.junit.Test
	public void test1() {
		ListNode ln1 = new ListNode(3);
		ListNode ln2 = new ListNode(2);
		ListNode ln3 = new ListNode(0);
		ListNode ln4 = new ListNode(-4);
		ln1.next = ln2;
		ln2.next = ln3;
		ln3.next = ln4;
		ln4.next = ln2;
		System.out.println(hasCycle1(ln1));
		System.out.println(hasCycle2(ln1));
	}

	@org.junit.Test
	public void test2() {
		ListNode ln1 = new ListNode(1);
		ListNode ln2 = new ListNode(2);
		ln1.next = ln2;
		ln2.next = ln1;
		System.out.println(hasCycle1(ln1));
		System.out.println(hasCycle2(ln1));
	}

	@org.junit.Test
	public void test3() {
		ListNode ln1 = new ListNode(1);
		ln1.next = null;
		System.out.println(hasCycle1(ln1));
		System.out.println(hasCycle2(ln1));
	}

	public boolean hasCycle1(ListNode head) {
		Set<ListNode> nodesSeen = new HashSet<>();
		while (head != null) {
			if (nodesSeen.contains(head)) {
				return true;
			} else {
				nodesSeen.add(head);
			}
			head = head.next;
		}
		return false;
	}

	public boolean hasCycle2(ListNode head) {
		if (head == null || head.next == null) {
			return false;
		}
		ListNode slow = head;
		ListNode fast = head.next;
		while (slow != fast) {
			if (fast == null || fast.next == null) {
				return false;
			}
			slow = slow.next;
			fast = fast.next.next;
		}
		return true;
	}
}

 

LeetCode_141. Linked List Cycle

原文:https://www.cnblogs.com/denggelin/p/11664650.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!