剑指offer--面试题5:从尾到头打印链表--Java实现

来源:互联网 发布:淘宝水杯 编辑:程序博客网 时间:2024/05/19 12:15

题目描述:
输入一个链表的头结点,从尾到头反过来打印出每个节点的值。

解题思路:
遍历链表,入栈,依次出栈,打印结果。

import java.util.Stack;public class PrintListReversingly {    static class ListNode{        int mKey;        ListNode mNext;        public  ListNode(){            this(0);        }        public ListNode(int key){            this.mKey = key;            this.mNext = null;        }    }    public static void print(ListNode node){        Stack<Integer> stack = new Stack<Integer>();        while(node != null){            stack.push(node.mKey);            node = node.mNext;        }        Integer value;        while(!stack.empty()){            value = stack.pop();            System.out.println(value);        }    }    public static void main(String[] args) {        // TODO Auto-generated method stub        //构造一个链表,用于测试        ListNode p = new ListNode();        ListNode head = p;        for(int i = 1; i < 10; i++){            ListNode node = new ListNode(i);            p.mNext = node;            p = p.mNext;        }        print(head);    }}
0 0
原创粉丝点击