본문 바로가기

Algorithms/Cracking the Coding Interview

Linked Lists: Detect a Cycle

A linked list is said to contain a cycle if any node is visited more than once while traversing the list.

Complete the function provided in the editor below. It has one parameter: a pointer to a Node object named that points to the head of a linked list. Your function must return a boolean denoting whether or not there is a cycle in the list. If there is a cycle, return true; otherwise, return false.

Note: If the list is empty,  will be null.

Input Format

Our hidden code checker passes the appropriate argument to your function. You are not responsible for reading any input from stdin.

Constraints

Output Format

If the list contains a cycle, your function must return true. If the list does not contain a cycle, it must return false. The binary integer corresponding to the boolean value returned by your function is printed to stdout by our hidden code checker.

Sample Input

The following linked lists are passed as arguments to your function:

Sample Inputs

Sample Output

0
1

Explanation

  1. The first list has no cycle, so we return false and the hidden code checker prints  to stdout.
  2. The second list has a cycle, so we return true and the hidden code checker prints  to stdout.


풀이


/*

Detect a cycle in a linked list. Note that the head pointer may be 'null' if the list is empty.


A Node is defined as: 

    class Node {

        int data;

        Node next;

    }

*/


boolean hasCycle(Node head) {

    if(head == null){

        return false;

    }

    Node current = head;

    Node currentNext = head.next;

    while(currentNext != null && currentNext.next != null){

        current = current.next;

        currentNext = currentNext.next.next;

        if(current == currentNext) return true;

    }

    return false;

}


처음에 문제 이해를 잘 하지 못해서 먼산으로...


linkedlist가 cycle인지 (loop로 도는지) 확인하는 문제로


현재 노드와 현재 노드의 다음 다음 노드가 같다면 (루프) cycle로 탐지해서 true 반환

'Algorithms > Cracking the Coding Interview' 카테고리의 다른 글

Queues: A Tale of Two Stacks  (0) 2018.02.20
Stacks: Balanced Brackets  (0) 2018.02.19
Hash Tables: Ransom Note  (0) 2018.02.09
Strings: Making Anagrams  (0) 2018.02.09
Arrays: Left Rotation  (0) 2018.02.08