从尾到头打印链表

来源:互联网 发布:智能电网技术知乎 编辑:程序博客网 时间:2024/05/29 17:53
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);    }}

0 0