逆序访问单链表

This is a simple but important algorithm when dealing with singly linked list.

This algorithms can reversely access a singly linked list using O(n) time. Below is my code in Java.

class Node{
    Node next;
    int val;
}

class SinglyLinkedList{
    
    Node head;
    Node tail;
    
    //append a new Node to tail
    void append(Node nd){
        
        //head and tail must both be null or both be not null
        if(head == null && tail == null){
            head = nd;
            tail = nd;
            
        }else{
            tail.next = nd;
            tail = nd;
        }
    }

    void print(){
        Node temp = head;
        while(temp != null){
            System.out.print(temp.val + " ");
            temp = temp.next;
        }
    }
    
    void printInReverseOrder(){
        printInReverseOrder_General(head);
    }

    void printInReverseOrder_General(Node from){
        if(from == null){
            return;
        }
        Node temp = from;
        
        printInReverseOrder_General(temp.next);
        System.out.print(temp.val + " ");
        
    }
}
原文地址:https://www.cnblogs.com/Antech/p/3657849.html