反向打印链表(单一和双重)的最佳方法是什么?

时间:2015-11-03 03:18:37

标签: java recursion linked-list

有人可以提供在Java中反向打印Linkedlist的可能方法。 我理解的方法是递归到达列表的末尾,然后从后面开始打印并递归地前进。 请分享可能的方式。

我正在使用具有下一个和上一个的节点。

我想到的解决方案如下。但是在这里我需要在每次进入递归循环时创建一个变量。那很糟糕:(

public void reversePrinting(int count){
        if(count==0){       //to assign the root node to current only once
            current=root;
            count++;
        }
        else{               //moving current node to subsequent nodes
        current=current.nextNode;
        }
        int x= current.data;
        if(current.nextNode==null){
            System.out.println(x);
            return;
        }
        reversePrinting(count);
            System.out.println(x);
    }

2 个答案:

答案 0 :(得分:0)

试试这个,它可以反转一个链表

public class DoReverse{ 
    private Node head; 
    private static class Node {
        private int value; 
        private Node next; 
        Node(int value) { 
            this.value = value; 
            } 
        } 
    public void addToTheLast(Node node) { 
        if (head == null) {
            head = node; 
        } 
        else { 
            Node temp = head;
            while (temp.next != null) 
                temp = temp.next; 
            temp.next = node; 
            } 
        } 
    public void printList(Node head) { 
        Node temp = head; 
        while (temp != null) { 
            System.out.format("%d ", temp.value); 
            temp = temp.next; 
            } 
        System.out.println(); 
        } 

    public static Node reverseList(Node head){

        Node prev = null;
        Node current = head;
        Node next = null;

        while(current != null){
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        head = prev;
        return head;

    }

    public static void main(String[] args) { 
        DoReverse list = new DoReverse(); 
        // Creating a linked list 
        Node head = new Node(5);
        list.addToTheLast(head); 
        list.addToTheLast(new Node(6)); 
        list.addToTheLast(new Node(7)); 
        list.addToTheLast(new Node(1)); 
        list.addToTheLast(new Node(2)); 
        list.addToTheLast(new Node(10));
        System.out.println("Before Reversing :");
        list.printList(head); 


        Node reverseHead= list.reverseList(head);
        System.out.println("After Reversing :");
        list.printList(reverseHead);


        } 
}

答案 1 :(得分:0)

为什么不复制列表以使其反转:

Reversing a linked list in Java, recursively

然后像往常那样循环列表的副本?