题目描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
code:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null)
return false;
ListNode snode = head;
ListNode fnode = head;
while(fnode != null && fnode.next != null)
{
fnode = fnode.next.next;
snode = snode.next;
if(snode == fnode)
return true;
}
return false;
}
}use a fast node and a slow node, if the fast node can match the slow node, then it can be concluded that it has a cycle.
本文介绍了一种使用快慢指针的方法来判断链表中是否存在循环。通过一个快速节点和一个慢速节点遍历链表,如果两者相遇则表明链表有循环。

被折叠的 条评论
为什么被折叠?



