공부기록

Linked List 본문

CS/Data Structure

Linked List

코타쿠 2021. 5. 29. 22:15

Linked List?

구현

public class SinglyLinkedList<E> {

    private static class Node<E>{
        private E element;
        private Node<E> next;
        public Node(E e, Node<E> n){
            element = e;
            next = n;
        }
        public E getElement(){
            return element;
        }
        public Node<E> getNext(){
            return next;
        }
        public void setNext(Node<E> n){
            next = n;
        }
    }

    private Node<E> head = null;
    private Node<E> tail = null;
    private int size = 0;
    public SinglyLinkedList(){}

    public int size(){
        return size;
    }

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

    public E last(){
        if(isEmpty())
            return null;
        return tail.getElement();
    }

    public void addFirst(E e){
        head = new Node<>(e, head);
        if(size == 0)
            tail = head;
        size++;
    }

    public void addLast(E e){
        Node<E> newest = new Node<>(e, null);
        if(isEmpty())
            head = newest;
        else
            tail.setNext(newest);
        tail = newest;
        size++;
    }

    public E removeFirst(){
        if(isEmpty())
            return null;
        E answer = head.getElement();
        head = head.getNext();
        size--;
        if(size == 0)
            tail = null;
        return answer;
    }

}

'CS > Data Structure' 카테고리의 다른 글

Sorting  (0) 2021.05.30
Queue  (0) 2021.05.29
Stack  (0) 2021.05.29
Hash  (0) 2021.05.28
Heap  (0) 2021.05.28