LeetCode——Linked List Cycle

Posted Brenda

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode——Linked List Cycle相关的知识,希望对你有一定的参考价值。

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

Follow up:

Can you solve it without using extra space?

原题链接:https://oj.leetcode.com/problems/linked-list-cycle/

题目:给定一个链表。推断它是否有环。

继续:

你能不用额外的空间解决吗?

思路:使用两个指针fast,slow,fast每次向前走两步,slow每次向前走一步。假设二者相应的节点相等。即存在环。

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

	// Definition for singly-linked list.
	class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
			next = null;
		}
	}


以上是关于LeetCode——Linked List Cycle的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode——Linked List Cycle

LeetCode2.Linked List — Linked List Cycle II 链表环2

[leetcode]Linked List-237. Delete Node in a Linked List

LeetCode27.Linked List—Reverse Linked List l链表逆置

LeetCode 328. Odd Even Linked List

LeetCode OJ 328Odd Even Linked List