Reversing a linked list or singly linked list using add, reverse and print method in java?

Please check my code. I wanted to do reverse a list using single input from user like on every do while user must enter y or Y to perform reverse after user clicks n but in my code the do while loop condition works after user enters 2 inputs. In the code i wanted the node method along with add,reverse and print method in it

import java.util.*;
public class Main
{
    static class Node {

        private int data;
        private Node next;

        public Node(int data) {
            this.data = data;
        }

        public int data() {
            return data;
        }

        public Node next() {
            return next;
        }
    }

    private Node head;

    public Main(Node head) {
        this.head = head;
    }

    public void add(Node node) {
        Node current = head;
        while (current != null) {
            if (current.next == null) {
                current.next = node;
                break;
            }
            current = current.next;
        }
    }

    public void print() {
        Node node = head;
        while (node != null) {
            System.out.print(node.data() + " ");
            node = node.next();
        }
        System.out.println("");
    }

    public void reverse() {
        Node pointer = head;
        Node previous = null, current = null;

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

            // reverse the link
            current.next = previous;
            previous = current;
            head = current;
        }
    }

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);
        char x;
        Main.Node head = new Main.Node(sc.nextInt());
        Main linkedlist = new Main(head);

        do
        {
            System.out.println("Do you want to continue");

            x=sc.next().charAt(0);
            linkedlist.add(new Main.Node(sc.nextInt()));
            //break;

        } while(x=='Y' || x=='y');

        linkedlist.reverse();

        linkedlist.print();
    }
}

Original output:

1
2
Do you want to continue
y
3
n
1 2 3
3 2 1

Expected output (I am not getting the expected output)

1 
Do you want to continue
y
2
Do you want to continue
y
3
Do you want to continue
n
1 2 3
3 2 1

1 answer

  • answered 2019-07-18 18:19 Jim Mischel

    I think what you're looking for is a while loop:

    x = "y";
    while (x == "y" || x == "Y")
    {
        linkedlist.add(new Main.Node(sc.nextInt()));
        System.out.println("Do you want to continue");
        x=sc.next().charAt(0);
    }