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

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 stack = new Stack(); ListNode p = head; while(p != null){ stack.push(p.value); p = p.next; } while(!stack.isEmpty()){ System.out.print(stack.pop() + " "); } } }
 
  
 
 

你可能感兴趣的:(剑指offer)