Insert a Node at the Tail of a Linked List

  • + 0 comments

    import java.io.; import java.util.;

    public class Solution {

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        LinkedList<Integer> list = new LinkedList<>();
        int n = Integer.parseInt(reader.readLine());
    
        for(int i = 0; i<n; i++){
            int value = Integer.parseInt(reader.readLine());
            list.add(value);
        }
    
        list.printValues();
    }
    

    }

    class Node{ private T value; private Node nextNode;

    public Node(T value){
        this.value = value;
        this.nextNode = null;
    }
    
    public Node<T> getNextNode(){
        return nextNode;
    }
    
    public void setNextNode(Node<T> nextNode){
        this.nextNode = nextNode;
    }
    
    public T getValue(){
        return value;
    }
    

    }

    class LinkedList{ Node head, tail;

    public LinkedList(){
        this.head = null;
        this.tail = null;
    }
    
    public void add(T value){
        Node<T> newNode = new Node<>(value);
        if(head == null){
            head = tail = newNode;
        }else{
            tail.setNextNode(newNode);
            tail = newNode;
        }
    }
    
    public void printValues(){
        Node<T> current = head;
        StringBuilder ret = new StringBuilder();
        while(current != null){
            ret.append(current.getValue()).append('\n');
            current = current.getNextNode();
        }
        System.out.println(ret.toString());
    }
    

    }