首页 > 其他 > 详细

逆序访问单链表

时间:2014-04-11 08:10:02      阅读:499      评论:0      收藏:0      [点我收藏+]

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.

bubuko.com,布布扣
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 + " ");
        
    }
}
bubuko.com,布布扣

 

逆序访问单链表,布布扣,bubuko.com

逆序访问单链表

原文:http://www.cnblogs.com/Antech/p/3657849.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!