카테고리 없음

[JAVA자료구조]1.리스트-원형연결리스트

인생개발 이정환 2024. 8. 17. 14:44
public class CircularLinkedList {
    // 노드 클래스
    static class Node {
        int data;
        Node next;

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

    private Node head = null;
    private Node tail = null;

    // 원형 연결 리스트에 노드 추가
    public void append(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = tail = newNode;
            tail.next = head; // 마지막 노드가 첫 번째 노드를 가리키도록 설정
        } else {
            tail.next = newNode;
            tail = newNode;
            tail.next = head; // 새 tail이 원형 연결을 유지하도록 설정
        }
    }

    // 노드 삭제
    public void delete(int data) {
        if (head == null) return; // 리스트가 비어 있을 경우

        Node current = head;
        Node previous = tail;

        // 리스트를 순회하여 삭제할 노드를 찾습니다.
        do {
            if (current.data == data) {
                if (current == head) {
                    // 삭제할 노드가 head인 경우
                    if (head == tail) {
                        // 리스트에 노드가 하나만 있는 경우
                        head = tail = null;
                    } else {
                        head = head.next;
                        tail.next = head;
                    }
                } else if (current == tail) {
                    // 삭제할 노드가 tail인 경우
                    tail = previous;
                    tail.next = head;
                } else {
                    // 삭제할 노드가 중간에 있는 경우
                    previous.next = current.next;
                }
                return; // 삭제 후 종료
            }
            previous = current;
            current = current.next;
        } while (current != head); // head로 돌아올 때까지 반복
    }

    // 원형 연결 리스트를 순회하며 출력
    public void printList() {
        if (head == null) return; // 리스트가 비어 있을 경우

        Node current = head;
        do {
            System.out.print(current.data + " ");
            current = current.next;
        } while (current != head); // head로 돌아올 때까지 반복
        System.out.println();
    }

    // 테스트
    public static void main(String[] args) {
        CircularLinkedList cll = new CircularLinkedList();
        cll.append(1);
        cll.append(2);
        cll.append(3);
        cll.append(4);

        System.out.println("Circular Linked List:");
        cll.printList();

        cll.delete(3);
        System.out.println("After deleting 3:");
        cll.printList();

        cll.delete(1);
        System.out.println("After deleting 1:");
        cll.printList();

        cll.delete(4);
        System.out.println("After deleting 4:");
        cll.printList();
    }
}