Java反向顺序的单链表

时间:2018-12-13 14:43:27

标签: java

如何编写代码以相反的顺序打印单个链表?

private class Elem {

    private int data;
    private Elem next;

    public Elem(int data, Elem next) {
        this.data = data;
        this.next = next;

    }

    public Elem(int data) {
        this(data, null);
    }
}
private Elem first = null, last = null;

1 个答案:

答案 0 :(得分:4)

您可以编写一个递归方法:

public static void printReversed (Elem start)
{
    if (start.next != null) {
        printReversed(start.next); // print the rest of the list in reversed order
    }
    System.out.println(start.data); // print the first element at the end
}