zoukankan      html  css  js  c++  java
  • 逆序访问单链表

    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 + " ");
            
        }
    }
  • 相关阅读:
    C++--第25课
    C++--第24课
    C++--第23课
    C++--第22课
    C++--第21课
    C++--第20课
    C++--第19课
    C++--第18课
    C++--第17课
    Windows程序设计学习笔记(1):一个简单的windows程序
  • 原文地址:https://www.cnblogs.com/Antech/p/3657849.html
Copyright © 2011-2022 走看看