您的位置:首页 > 职场人生

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

2016-11-14 10:07 627 查看
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 staticvoid 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() + " "); } }}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: