使用Java中的添加,反转和打印方法来反转链表或单链表?

时间:2019-07-18 15:13:54

标签: java data-structures

请检查我的代码。我想使用用户的单个输入来反转列表,就像每次执行操作一样,而用户单击n后用户必须输入y或Y才能执行反向操作,但是在我的代码中,用户输入2个输入后do while循环条件有效。在代码中,我想要node方法以及其中的add,reverse和print方法

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();
    }
}

原始输出:

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

期望的输出(我没有得到期望的输出)

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 个答案:

答案 0 :(得分:0)

我认为您正在寻找的是while循环:

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);
}