從尾到頭打印鏈表

package java_study.JianZhiOffer;

import org.junit.Test;

import java.util.Random;
import java.util.Stack;

/**
 * Created by ethan on 2015/6/21.
 * 劍指offer No5 鏈表的逆序輸出
 */
public class No5PrintListInReverse {
    public Node listNode = init(10);
    public Node init(int len){
        Node head = new Node();
        Node tmp = head;
        Random random = new Random();
        for (int i=0; i<len; i++){
            Node node = new Node(random.nextInt(30));
            tmp.setNext(node);
            tmp = tmp.getNext();
        }
        return head.getNext();
    }

    // 遞歸實現
    public void printListInReverseOrder(Node listNode){
        if (listNode==null)
            return;
        printListInReverseOrder(listNode.getNext());
        System.out.print(listNode.getValue()+ " ");
    }
    // 這種遞歸的實現更加接近想法
    public void printListInReverseOrder_1(Node listNode){
        if (listNode!=null){
            if (listNode.getNext()!=null){
                printListInReverseOrder_1(listNode.getNext());
            }
            System.out.print(listNode.getValue()+ " ");
        }
    }
    // 棧實現
    public void printListInReverseOrder_stack(Node listNode){
        if (listNode == null) return;
        Stack<Integer> stack = new Stack<Integer>();
        while (listNode!=null){
            stack.push(listNode.getValue());
            listNode = listNode.getNext();
        }
        while (!stack.isEmpty()){
            System.out.print(stack.pop() + " ");
        }
        System.out.println();
    }

    public void print_linkedList(Node listNode){
        while (listNode!=null){
            System.out.print(listNode.getValue() + " ");
            listNode = listNode.getNext();
        }
        System.out.println();
    }

    @Test
    public void test(){
        print_linkedList(listNode);
        printListInReverseOrder_stack(listNode);
        printListInReverseOrder(listNode);
        System.out.println();
        printListInReverseOrder_1(listNode);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章