java - 如何在 Java 中不使用递归打印反向链表?

标签 java recursion linked-list iteration singly-linked-list

我尝试在没有递归的情况下打印反向链表并反转链表。我该怎么做?

问题:如何在不使用递归且不反转列表的情况下打印反向链表?

要求:没有多余的空格,不能反转链表,不能使用递归。

这里是链表节点的定义

class Node {
  int value;
  Node next;

  public Node(int val) {
    this.value = val;
  }
}

这是我的 printReverseLinkedList 的递归版本:

public void printReverseList(Node head) {
    Node temp = head;
    if (temp.next != null) {
        printReverseList(temp.next);
    }
    System.out.print(temp.value);
}

性能无所谓,因为我只想做成这样。

最佳答案

如果您既不能反转列表,也不能使用递归,那么唯一的方法是:

public void printReversList(Node head) {

    Node current = head; // used to search through the list
    Node last    = null; // stores the last element that we printed

    while (last != head) { // = we didn't print everything yet

        // find next element to print - it's one element before we reach "last"
        while (current.next != last) {
            current = current.next;
        }

        // Store the current element as the new last and print it
        last  = current;
        system.out.print(last.value);

        // reset current and start all over
        current = head;
    }
}

非常无效,但我想不出其他办法。

关于java - 如何在 Java 中不使用递归打印反向链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37706805/

相关文章:

php - 对话的数据库逻辑(如论坛)PHP、MySql

go - 在 slice 上运行递归函数时发生意外行为

java - java中自定义链接列表的自定义值类

c - C中从文件中读取各种形式的数据并存储在链表中

java - 使用正则表达式替换某个字符串 - Java

java - Kotlin java.lang.NoSuchMethodException:<init>()

.net 3.5 中深度/递归对象比较的 C# 实现

c - 删除链表最后一项

java - 实体管理器不会像插入的那样返回所有元素

java - 异常 : javax. resource.spi.ResourceAdapterInternalException:意外错误