개발팁/Java

[Java] 최적화된 Linked List 알고리즘

후앤하 2022. 12. 16. 20:11
반응형

 

 

다음은 그 사용법을 보여주는 간단한 단위 테스트와 함께 Java로 단일 연결 목록을 구현한 것입니다.


public class LinkedList {
    private Node head;
    private int size;

    public LinkedList() {
        head = null;
        size = 0;
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void add(int data) {
        Node newNode = new Node(data);
        newNode.setNext(head);
        head = newNode;
        size++;
    }

    public void remove(int data) {
        if (head == null) return;
        if (head.getData() == data) {
            head = head.getNext();
            size--;
            return;
        }

        Node current = head;
        while (current.getNext() != null) {
            if (current.getNext().getData() == data) {
                current.setNext(current.getNext().getNext());
                size--;
                return;
            }
            current = current.getNext();
        }
    }

    public boolean contains(int data) {
        Node current = head;
        while (current != null) {
            if (current.getData() == data) {
                return true;
            }
            current = current.getNext();
        }
        return false;
    }

    private class Node {
        private int data;
        private Node next;

        public Node(int data) {
            this.data = data;
            this.next = null;
        }

        public int getData() {
            return data;
        }

        public void setData(int data) {
            this.data = data;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }
}

 

 

 

 

 

 

 

다음은 LinkedList 클래스의 사용을 보여주는 간단한 단위 테스트입니다.

 

 

public class LinkedListTest {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();

        // Add some elements to the list
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);

        // Print the size of the list
        System.out.println("Size of list: " + list.getSize());

        // Print the contents of the list
        System.out.println("Contents of list: " + list);

        // Remove an element from the list
        list.remove(2);

        // Print the size of the list
        System.out.println("Size of list: " + list.getSize());

        // Print the contents of the list
        System.out.println("Contents of list: " + list);

        // Check if the list contains a given element
        System.out.println("List contains 1: " + list.contains(1));
        System.out.println("List contains 2: " + list.contains(2));
    }
}
반응형