단방향 Linked List 구현

김아무개·2023년 6월 10일
0

자료구조

목록 보기
10/10

코드를 자주 읽어봐야 할 필요성을 크게 느껴서 포스팅 🐢

구현하는데 너무 어려웠다.

노드로 값을 확인하고 삭제하고 추가하는게 아직까지도 낯설다 😬

자주 읽어봐야 됨

코드 작성

Node

class Node<T> {
    T data;
    Node<T> next;

    public Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }
}

LinkedList

class MyLinkedList<T> {

    private Node<T> head;
    private int size;

    public MyLinkedList() {
        this.head = null;
        this.size = 0;
    }

	// add ============================================================================
    public T add(T value) {

        if (head == null) {
            head = new Node<>(value, null );

        } else {
            Node<T> current = head;

            while (current.next != null)
                current = current.next;

            current.next = new Node<>(value, null);
        }

        size++;
        return value;
    }
    public T add(int index, T value) {
        if (index == 0)
            head = new Node<>(value, head);

        else if (head == null) {
            System.out.printf(
                    "[ add 실패 : index %d , value %s] 리스트가 비어있음\n",
                    index,
                    value
            );

            return null;
        } else if (index > size) {
            System.out.printf(
                    "[ add 실패 : index %d , value %s] index가 list 크기를 벗어남\n",
                    index,
                    value
            );

            return null;
        } else {
            int idx = 0;
            Node<T> prevNode, nextNode;
            Node<T> current = head;

            while (current != null) {
                if (idx + 1 == index) {
                    prevNode = current;
                    nextNode = current.next;

                    prevNode.next = new Node<>(value, nextNode);

                    break;
                }

                current = current.next;
                idx++;
            }
        }

        size++;
        return value;
    }
	// ============================================================================ add

	// remove =========================================================================
    public T remove() {

        if (head == null) {
            System.out.println("[ remove ] 리스트가 이미 비어있음");
            return null;

        } else {
            Node<T> prevNode = head;
            Node<T> current = head;

            while (current.next != null) {
                prevNode = current;
                current = prevNode.next;
            }

            T value = current.data;

            if (current == head)
                head = null;
            else
                prevNode.next = null;

            size--;
            return value;
        }
    }
    public T remove(T value) {

        if (head == null) {
            System.out.println("[ remove : " + value + " 실패 ] 리스트가 비어있음");
            return null;

        } else if (!contains(value)) {
            System.out.println("[ remove : " + value + " 실패 ] " + value + " 없음");
            return null;

        } else {
            Node<T> prevNode = head;
            Node<T> current = head;

            while (current != null) {
                if (current.data.equals(value)) {
                    if (current == head)
                        head = current.next;
                    else
                        prevNode.next = current.next;

                    size--;
                    break;
                }

                prevNode = current;
                current = prevNode.next;
            }

            return value;
        }
    }
	// ========================================================================= remove

    public boolean contains(T value) {
        Node<T> current = head;
        while (current != null) {
            if (current.data.equals(value))
                return true;

            current = current.next;
        }

        return false;
    }

    public void clear() {
        head = null;
        size = 0;
    }

    public boolean isEmpty() {
        return head == null;
    }
    public int size() {
        return size;
    }

	// sout + this.toString ========================================================= 
    public void print() {
        System.out.println(this);
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder("LinkedListt : [ ");

        if (head == null) {
            sb.append("]");

        } else {
            Node<T> current = head;
            do {
                sb.append(current.data).append(", ");

                current = current.next;
            } while (current != null);

            sb.deleteCharAt(sb.lastIndexOf(", ")).append("]");
        }
        sb.append("\n");
        sb.append("       size : ").append(size);
        sb.append("\n");

        return sb.toString();
    }
	// ========================================================= sout + this.toString 
}

실행 확인

public class LinkedListt {

    public static void main(String[] args) {
        MyLinkedList<Integer> list = new MyLinkedList<>();

        // linkedList 정보 조회
        list.print();
        // LinkedListt : [ ]
        //        size : 0

        System.out.println("add : " + list.add(1));
        list.print();
         // add : 1
        // LinkedListt : [ 1 ]
        //        size : 1

        System.out.println("add : " + list.add(2));
        list.print();
        // add : 2
        // LinkedListt : [ 1, 2 ]
        //        size : 2 

        System.out.println("add : index 0 , value " + list.add(0, 0));
        list.print();
        // add : index 0 , value 0
        // LinkedListt : [ 0, 1, 2 ]
        //        size : 3

        System.out.println("add : index 4 , value " + list.add(4, 4));
        list.print();
        // [ add 실패 : index 4 , value 4] index가 list 크기를 벗어남
        // add : index 4 , value null
        // LinkedListt : [ 0, 1, 2 ]
        //        size : 3

        System.out.println("add : index 3 , value " + list.add(3, 3));
        list.print();
        // add : index 3 , value 3
        // LinkedListt : [ 0, 1, 2, 3 ]
        //        size : 4

        System.out.println("isEmpty : "+ list.isEmpty());
        // isEmpty : false

        System.out.println("size : "+ list.size());
        // size : 4
        
        System.out.println("contains 2 : "+ list.contains(2));
        // contains 2 : true
        
        System.out.println("contains 4 : "+ list.contains(4));
        // contains 4 : false

        System.out.println();
        
        System.out.println("clear");
        list.clear();
        list.print();
        // clear
        // LinkedListt : [ ]
        //        size : 0

        System.out.println("isEmpty : "+ list.isEmpty());
        System.out.println();
        // isEmpty : true

        System.out.println("add : index 3 , value " + list.add(3, 2));
        list.print();
        // [ add 실패 : index 3 , value 2] 리스트가 비어있음
        // add : index 3 , value null
        // LinkedListt : [ ]
        //        size : 0

        System.out.println("add : index 0 , value " + list.add(0, 11));
        list.print();
        // add : index 0 , value 11
        // LinkedListt : [ 11 ]
        //        size : 1

        System.out.println("add : " + list.add(1));
        list.print();
        // add : 1
        // LinkedListt : [ 11, 1 ]
        //        size : 2

        System.out.println("add : " + list.add(2));
        list.print();
        // add : 2
        // LinkedListt : [ 11, 1, 2 ]
        //        size : 3

        System.out.println("add : index 0 , value " + list.add(0, 0));
        list.print();
        // add : index 0 , value 0
        // LinkedListt : [ 0, 11, 1, 2 ]
        //        size : 4

        System.out.println("add : " + list.add(3));
        list.print();
        // add : 3
        // LinkedListt : [ 0, 11, 1, 2, 3 ]
        //        size : 5

        System.out.println("add : " + list.add(4));
        list.print();
        // add : 4
        // LinkedListt : [ 0, 11, 1, 2, 3, 4 ]
        //        size : 6

        System.out.println("isEmpty : " + list.isEmpty());
        System.out.println("remove : " + list.remove(4));
        list.print();
        // isEmpty : false
        // remove : 4
        // LinkedListt : [ 0, 11, 1, 2, 3 ]
        //        size : 5

        System.out.println("remove : " + list.remove(2));
        list.print();
        // remove : 2
        // LinkedListt : [ 0, 11, 1, 3 ]
        //        size : 4

        System.out.println("remove : " + list.remove(0));
        list.print();
        // remove : 0
        // LinkedListt : [ 11, 1, 3 ]
        //        size : 3

        System.out.println("remove last : " + list.remove());
        list.print();
        // remove last : 3
        // LinkedListt : [ 11, 1 ]
        //        size : 2

        System.out.println("add : index 0 , value " + list.add(0, 4));
        list.print();
        // add : index 0 , value 4
        // LinkedListt : [ 4, 11, 1 ]
        //        size : 3

        System.out.println("remove last : " + list.remove());
        list.print();
        // remove last : 1
        // LinkedListt : [ 4, 11 ]
        //        size : 2

        System.out.println("remove last : " + list.remove());
        list.print();
        // remove last : 11
        // LinkedListt : [ 4 ]
        //        size : 1

        System.out.println("remove : " + list.remove(11));
        list.print();
        // [ remove : 11 실패 ] 11 없음
        // remove : null
        // LinkedListt : [ 4 ]
        //        size : 1

        System.out.println("clear");
        list.clear();
        list.print();
        // clear
        // LinkedListt : [ ]
        //        size : 0

        System.out.println("remove : " + list.remove(11));
        list.print();
        // [ remove : 11 실패 ] 리스트가 비어있음
        // remove : null
        // LinkedListt : [ ]
        //        size : 0
    }
}
profile
Hello velog! 

0개의 댓글

관련 채용 정보