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

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

2015-04-24 21:31 781 查看
题目描述:

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

解题思路:

遍历链表,入栈,依次出栈,打印结果。

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);
}

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