package linkedlist;

public class Node<T> {

    private Node<T> next;

    private T value;

     

    public Node(T value, Node<T> next) {

        this.value = value;

        this.next = next;

    }

    public Node<T> getNext() {

        return next;

    }

    public void setNext(Node<T> next) {

        this.next = next;

    }

    public T getValue() {

        return value;

    }

    public void setValue(T value) {

        this.value = value;

    }

}

 

 

 

 

 

package linkedlist;

public class LinkedList2<T> {

    Node<T> head;

     

    public LinkedList2() {}

     

    public void addFirst(T value) {

        if (head == null) {

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

        } else {

            Node<T> newHead = new Node<T>(value, head);

            head = newHead;

        }

    }

}

 

 

 

 

 

public void print() {

    Node<T> lastNode = head;

    while (lastNode != null) {

        System.out.println(lastNode.getValue());     

        lastNode = lastNode.getNext();

    }

}

 

 

 

 

 

package linkedlist;

public class Main {

    public static void main(String[] args) {

        LinkedList2<String> list = new LinkedList2<>();

        list.addFirst("First value");

        list.addLast("Last value");

        list.addFirst("New first value");

        list.addLast("New last value");

        list.print();

    }

}