欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Linked List Cycle

程序员文章站 2022-07-09 23:53:46
...
Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

判断一个链表中是否有环存在,用快慢指针来解决,设定两个指针fast和slow都指向head,我们让fast = fast.next.next,slow = slow.next,如果存在环,fast和slow就会相遇,因此当fast == slow时我们就返回true, 否则返回false。代码如下:
/**
 * 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 || head.next == null) return false;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast)
                return true;
        }
        return false;
    }
}
相关标签: 链表