본문 바로가기
Algorithm

SingleLinkedList

by forkballpitch 2017. 6. 27.
반응형


public class SingleLinkedList {

 

    Node head;

    

        class Node{   // 노드 클래스 

            int data;

            Node next;

            

            Node(int i){

                this.data = i;

            }

        }

        

    public void add(int i){   // 리스트에 노드 추가 함수

        if(head == null){

            head = new Node(i);

        }

        else{

            Node temp = head;

            while(temp.next != null){

                temp = temp.next;

            }

            temp.next = new Node(i);        

        }

    }

    

    public void print(){  // 리스트 출력 함수 

        Node temp = head;

        while(temp != null){

            System.out.println(temp.data);

            temp = temp.next;

        }

    }

    

    public void makeLoop(){   // 루프를 만드는 메소드 

        Node temp = head;

        Node temp1 = head;

        

        for(int i = 0; i < 2; i++){

            temp = temp.next;

        }

        

        while(temp1.next != null){

            temp1 = temp1.next;

        }

        

        temp1.next = temp;

    }

    

    public boolean detect(){   // Loop 탐지하는 메소드 

        Node hare = head;

        Node tortoise = head;

        

        while(true){

            if(hare.next == null){

                return false;

            }

            hare = hare.next;

            

            if(hare.next == null){

                return false;

            }

            hare = hare.next;

            tortoise = tortoise.next;

            

            if(hare == tortoise){

                return true;

            }    

        }

    }

    

    public static void main(String[] args) {

    SingleLinkedList hello = new SingleLinkedList();

        hello.add(1);

        hello.add(2);

        hello.add(3);

        hello.add(4);

        hello.add(5);

        hello.add(6);

        hello.add(7);

        hello.add(8);

        hello.print();

        hello.makeLoop();

        System.out.println(hello.detect());

    }

 

}

 

 

반응형

'Algorithm' 카테고리의 다른 글

DFS_leetcode numofisland  (0) 2021.09.23
softeer 지도 자동 구축  (0) 2021.09.23
Bubble Sort  (0) 2017.09.26
insertion sort  (0) 2017.07.03
Binary Search 이분탐색  (0) 2017.06.27