Java中的单链表
如何编写以相反顺序打印单链表的代码Java中的单链表,java,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); } } pri
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;
您可以编写递归方法:
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
}
这可能是问题的标准解决方案,但让我们来解释一下:
1。检查列表中是否有其他元素,如果有,请先处理它。
,2。随后处理当前元素。
。