剑指offer 面试题5 从尾到头打印链表 java版答案

来源:互联网 发布:从数组中删除指定元素 编辑:程序博客网 时间:2024/05/18 19:41
package OfferAnswer;/** * 定义ListNode * @author lwk * */public class ListNode {    int value;    ListNode next;        public ListNode() {    }        public ListNode(int value) {    this.value = value;}}

package OfferAnswer;import java.util.Stack;/** * 面试题5 * 从尾到头打印链表 * @author lwk * */

public class Answer05 { public static void main(String[] args) {ListNode p1 = new ListNode(1);ListNode p2 = new ListNode(2);ListNode p3 = new ListNode(3);ListNode p4 = new ListNode(4);p1.next = p2;p2.next = p3;p3.next = p4;printReversely(p1);} public static void printReversely(ListNode head){ if(head == null){ return; } //栈 先进后出 Stack<Integer> stack = new Stack<Integer>(); ListNode p = head; while(p != null){ stack.push(p.value); p = p.next; } while(!stack.isEmpty()){ System.out.print(stack.pop() + " "); } } }
                                             
0 0