Algorithm/LeetCode

[LeetCode] - Linked List Cycle

JunGi Jeong 2021. 5. 11. 23:16

링크드 리스트이 반복적으로 순회하고 있다면 true 아니라면 false

 

Constraints:

  • The number of the nodes in the list is in the range [0, 10^4].
  • -105 <= Node.val <= 105
  • pos is -1 or a valid index in the linked-list.

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

 

제약 사항에 따라 최대 길이가 1만이기에 만 번 돌렸고 돌리는 중에 null이 있다면 순회가 되고 있지 않는다는 것이기에 null반환

그렇지 않다면 true

public class Solution {
    public boolean hasCycle(ListNode head) {
        for(int idx = 0; idx < 10000; idx++){
            if(head == null || head.next == null) return false;
            head = head.next;
        }
        return true;
    }
}