首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在不使用Java递归的情况下打印反向链接列表?

如何在不使用Java递归的情况下打印反向链接列表?
EN

Stack Overflow用户
提问于 2016-06-08 15:27:16
回答 5查看 6.3K关注 0票数 3

我尝试打印一个反向链表,没有递归和反向链表。我怎么能这么做?

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

Requirements:没有额外的空间,不能反向链接列表,不能使用递归。

下面是链接列表节点的定义

代码语言:javascript
运行
复制
class Node {
  int value;
  Node next;

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

下面是我的递归版本的printReverseLinkedList:

代码语言:javascript
运行
复制
public void printReverseList(Node head) {
    Node temp = head;
    if (temp.next != null) {
        printReverseList(temp.next);
    }
    System.out.print(temp.value);
}

性能并不重要,因为我只想这样做.

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-06-08 15:44:18

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

代码语言:javascript
运行
复制
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;
    }
}

这是非常无效的,但我没有其他办法可以想到。

票数 5
EN

Stack Overflow用户

发布于 2016-06-08 15:49:18

用一个堆栈然后弹出怎么样?你说过用另一种数据结构就行了。这不是很好的代码,但是,应该完成工作。

代码语言:javascript
运行
复制
public void printReversList(Node head) {

    Stack<Node> stack = new Stack<>();

    while (head != null){

       stack.push(head);
       head = head.next;          
   }

   while (!stack.isEmpty()){
       System.out.println(stack.pop());
   }
}
票数 3
EN

Stack Overflow用户

发布于 2016-06-08 15:42:58

你可以试试这个:

代码语言:javascript
运行
复制
public void printReverseList(Node head) {
            if(head == null) return;
            Node prev = null;
            Node revers = head;
            Node nex = null;

            while (revers != null){
                nex = revers.next;
                revers.next = prev;

                prev = revers;
                revers = nex;

            }
            System.out.println(prev);
        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37706805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档