leetcode linked list cycle

problem:

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

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

Hide Tags
 Linked List Two Pointers






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 fast=head,slow=head;
        do{
        if(fast.next==null || fast.next.next==null){
            return null;
        }
        fast=fast.next.next;
        slow=slow.next;
        }while(fast !=slow)
        return true;
    }
}

發佈了34 篇原創文章 · 獲贊 6 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章