//TestIntegerNodeSequence.java
//Illustrates recursion applied to a sequence of linked nodes

import java.util.Scanner;

public class TestIntegerNodeSequence
{
    private static Scanner keyboard = new Scanner(System.in);
    private static Scanner lineScanner = null;
    private static Node head = null;

    public static void main(String[] args)
    {
        System.out.println
        (
            "\nEnter four data values for the nodes "
            + "on the following line:"
        );
        String line = keyboard.nextLine();
        lineScanner = new Scanner(line);

        buildSequenceExplicitly();
        //buildSequenceIteratively();
        //buildSequenceRecursively();

        System.out.println
        (
            "\nHere, from the linked nodes, are the "
            + "values read in, first in the order\nin which they "
            + "appear in the sequence, then in that order reversed:"
        );
        displaySequenceValues(head);
        System.out.println();
        displaySequenceValuesInReverseOrder(head);

        System.out.print("\nPress Enter to continue ... ");
        keyboard.nextLine();
    }

    public static void buildSequenceExplicitly()
    {
        head = null;
        if (lineScanner.hasNextInt())
            head = new Node(lineScanner.nextInt(), head);
        if (lineScanner.hasNextInt())
            head = new Node(lineScanner.nextInt(), head);
        if (lineScanner.hasNextInt())
            head = new Node(lineScanner.nextInt(), head);
        if (lineScanner.hasNextInt())
            head = new Node(lineScanner.nextInt(), head);
    }

    public static void buildSequenceIteratively()
    {
        head = null;
        while (lineScanner.hasNextInt())
            head = new Node(lineScanner.nextInt(), head);
    }

    public static void buildSequenceRecursively()
    {
        if (lineScanner.hasNextInt())
        {
            int value = lineScanner.nextInt();
            buildSequenceRecursively();
            head = new Node(value, head);
        }
        else
        {
            head = null;
        }
    }

    public static void displaySequenceValues(Node head)
    {
        if (head != null)
        {
            System.out.print(head.data + " ");
            displaySequenceValues(head.next);
        }
    }

    public static void displaySequenceValuesInReverseOrder(Node head)
    {
        if (head != null)
        {
            displaySequenceValuesInReverseOrder(head.next);
            System.out.print(head.data + " ");
        }
    }

    private static class Node
    {
        private int  data; //Data in the node
        private Node next; //Link to next node

        //Two constructors
        public Node(int data)
        {
            this(data, null);
        }
        public Node(int data, Node next)
        {
            this.data = data;
            this.next = next;
        }
    }
}

