자료구조&알고리즘

[JAVA자료구조]1. 리스트-단순연결리스트

인생개발 이정환 2024. 8. 17. 14:41
class Node {
    int data;  // 노드가 저장할 데이터
    Node next; // 다음 노드를 가리키는 참조

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

class SinglyLinkedList {
    private Node head;  // 리스트의 첫 번째 노드를 가리키는 참조

    // 생성자: 새로운 연결 리스트를 초기화 (비어 있는 상태)
    public SinglyLinkedList() {
        this.head = null;
    }

    // 리스트의 시작 부분에 새로운 노드를 추가하는 메서드
    public void insertAtBeginning(int data) {
        Node newNode = new Node(data);
        newNode.next = head;
        head = newNode;
    }

    // 리스트의 끝 부분에 새로운 노드를 추가하는 메서드
    public void insertAtEnd(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    // 주어진 데이터를 가진 노드를 삭제하는 메서드
    public void delete(int data) {
        if (head == null) {
            System.out.println("리스트가 비어 있습니다.");
            return;
        }

        // 삭제할 노드가 첫 번째 노드인 경우
        if (head.data == data) {
            head = head.next;
            return;
        }

        Node current = head;
        Node previous = null;

        // 삭제할 노드를 찾기 위해 리스트를 순회
        while (current != null && current.data != data) {
            previous = current;
            current = current.next;
        }

        // 노드를 찾지 못한 경우
        if (current == null) {
            System.out.println("값 " + data + "을(를) 가진 노드를 찾을 수 없습니다.");
            return;
        }

        // 노드를 리스트에서 제거
        previous.next = current.next;
    }

    // 리스트의 모든 노드를 출력하는 메서드
    public void printList() {
        if (head == null) {
            System.out.println("리스트가 비어 있습니다.");
            return;
        }

        Node current = head;
        while (current != null) {
            System.out.print(current.data + " -> ");
            current = current.next;
        }
        System.out.println("null");
    }

    // 리스트의 크기를 조정하는 메서드
    public void resize(int newSize) {
        int currentSize = 0;
        Node current = head;
        Node previous = null;

        // 현재 리스트의 크기를 계산
        while (current != null) {
            currentSize++;
            previous = current;
            current = current.next;
        }

        // 새로운 크기가 현재 크기보다 작을 경우, 리스트를 자름
        if (newSize < currentSize) {
            current = head;
            previous = null;
            int count = 0;

            while (count < newSize) {
                previous = current;
                current = current.next;
                count++;
            }

            if (previous != null) {
                previous.next = null;  // 리스트 자르기
            } else {
                head = null;  // newSize가 0인 경우, 리스트를 비움
            }

        } else if (newSize > currentSize) {
            // 새로운 크기가 현재 크기보다 클 경우, 기본값 0으로 노드를 추가
            if (previous == null) {
                head = new Node(0);
                current = head;
            } else {
                current = previous;
            }

            for (int i = currentSize; i < newSize; i++) {
                current.next = new Node(0);
                current = current.next;
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        SinglyLinkedList list = new SinglyLinkedList();
        list.insertAtEnd(10);
        list.insertAtEnd(20);
        list.insertAtEnd(30);
        list.printList();  // 출력: 10 -> 20 -> 30 -> null

        list.insertAtBeginning(5);
        list.printList();  // 출력: 5 -> 10 -> 20 -> 30 -> null

        list.delete(20);
        list.printList();  // 출력: 5 -> 10 -> 30 -> null

        list.resize(5);
        list.printList();  // 출력: 5 -> 10 -> 30 -> 0 -> 0 -> null

        list.resize(2);
        list.printList();  // 출력: 5 -> 10 -> null
    }
}