문제

Java에서 연결 목록을 만드는 가장 좋은 방법은 무엇입니까?

도움이 되었습니까?

해결책

Java에 익숙한 개발자에게 확실한 솔루션은 다음을 사용하는 것입니다. 링크드리스트 이미 제공되는 클래스 java.util.그러나 어떤 이유로든 자신만의 구현을 만들고 싶었다고 가정해 보겠습니다.다음은 목록의 시작 부분에 새 링크를 삽입하고, 목록의 시작 부분에서 삭제하고, 목록을 반복하여 포함된 링크를 인쇄하는 연결 목록의 빠른 예입니다. 향상된 기능 이 구현에는 다음을 포함합니다. 이중 연결 목록, 메소드 추가 끼워 넣다 그리고 삭제 중간이나 끝에서 추가하여 얻다 그리고 종류 방법도 마찬가지다.

메모:예제에서 Link 개체는 실제로 다른 Link 개체를 포함하지 않습니다. 다음링크 실제로는 다른 링크에 대한 참조일 뿐입니다.

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;
        if(first == null){
         return null;
         //throw new NoSuchElementException(); // this is the better way. 
        }
        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();
    }
}

다른 팁

자바에는 링크드리스트 구현을 확인해 보세요.JDK와 소스는 다음에서 다운로드할 수 있습니다. java.sun.com.

사용 java.util.LinkedList.이와 같이:

list = new java.util.LinkedList()

위의 연결된 목록은 반대 방향으로 표시됩니다.삽입 메소드의 올바른 구현은 다음과 같아야 한다고 생각합니다.

public void insert(int d1, double d2) { 
    Link link = new Link(d1, d2); 

    if(first==null){
        link.nextLink = null;
        first = link; 
        last=link;
    }
    else{
        last.nextLink=link;
        link.nextLink=null;
        last=link;
    }
} 

java.util.LinkedList를 사용하는 것이 훨씬 더 좋습니다. 왜냐하면 여러분이 작성할 것보다 훨씬 더 최적화되어 있기 때문입니다.

//slightly improved code without using collection framework

package com.test;

public class TestClass {

    private static Link last;
    private static Link first;

    public static void main(String[] args) {

        //Inserting
        for(int i=0;i<5;i++){
            Link.insert(i+5);
        }
        Link.printList();

        //Deleting
        Link.deletefromFirst();
        Link.printList();
    }


    protected  static class Link {
        private int data;
        private Link nextlink;

        public Link(int d1) {
            this.data = d1;
        }

        public static void insert(int d1) {
            Link a = new Link(d1);
            a.nextlink = null;
            if (first != null) {
                last.nextlink = a;
                last = a;
            } else {
                first = a;
                last = a;
            }
            System.out.println("Inserted -:"+d1);
        }

        public static void deletefromFirst() {
            if(null!=first)
            {
                System.out.println("Deleting -:"+first.data);
                first = first.nextlink;
            }
            else{
                System.out.println("No elements in Linked List");
            }
        }

        public static void printList() {
            System.out.println("Elements in the list are");
            System.out.println("-------------------------");
            Link temp = first;
            while (temp != null) {
                System.out.println(temp.data);
                temp = temp.nextlink;
            }
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top