【问题标题】:Single Linked List in reverse order Java [closed]反向顺序Java的单链表[关闭]
【发布时间】:2019-05-14 19:37:09
【问题描述】:

如何编写逆序打印单链表的代码?

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;

【问题讨论】:

标签: java


【解决方案1】:

你可以写一个递归方法:

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. Check if there is another element in the list and if so process it first., 2. Process current element afterwards.
猜你喜欢
  • 1970-01-01
  • 2020-02-06
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
相关资源
最近更新 更多