. 자바에서 링크드리스트를 만드는 방법

조회수 3684회

자바에서 링크드리스트를 만드는 가장 좋은 방법은 뭔가요?

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    솔직히 가장 좋은 방법이라면 개발자에게는 java.util에서 제공하는 LinkedList클래스를 쓰는것입니다. 그러나 제가 보기엔 직접적인 구현 방법을 원하시는 것 같으니 간단한 예제를 드리겠습니다. 이 예제는 링크드리스트의 초입에 새로운 링크를 삽입하고 지울때도 리스트의 처음부분부터 루프를 돌아 해당하는 원소를 찾아 지우는 방식입니다. 더 발전시키면 더블링크드 리스트를 구현할수있습니다.

    class Link {
        public int data1;
        public double data2;
        public Link nextLink;
    
        //Link constructor
        public Link(int d1, double d2) {
            data1 = d1;
            data2 = d2;
        }
    
        //Print Link data
        public void printLink() {
            System.out.print("{" + data1 + ", " + data2 + "} ");
        }
    }
    
    class LinkList {
        private Link first;
    
        //LinkList constructor
        public LinkList() {
            first = null;
        }
    
        //Returns true if list is empty
        public boolean isEmpty() {
            return first == null;
        }
    
        //Inserts a new Link at the first of the list
        public void insert(int d1, double d2) {
            Link link = new Link(d1, d2);
            link.nextLink = first;
            first = link;
        }
    
        //Deletes the link at the first of the list
        public Link delete() {
            Link temp = first;
            first = first.nextLink;
            return temp;
        }
    
        //Prints list data
        public void printList() {
            Link currentLink = first;
            System.out.print("List: ");
            while(currentLink != null) {
                currentLink.printLink();
                currentLink = currentLink.nextLink;
            }
            System.out.println("");
        }
    }  
    
    class LinkListTest {
        public static void main(String[] args) {
            LinkList list = new LinkList();
    
            list.insert(1, 1.01);
            list.insert(2, 2.02);
            list.insert(3, 3.03);
            list.insert(4, 4.04);
            list.insert(5, 5.05);
    
            list.printList();
    
            while(!list.isEmpty()) {
                Link deletedLink = list.delete();
                System.out.print("deleted: ");
                deletedLink.printLink();
                System.out.println("");
            }
            list.printList();
        }
    }
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)