思路:从尾到头打印链表的值,我们只需要从头遍历链表,依次将链表中的结点的值放入到栈中,然后将栈中元素出栈打印,得到的就是逆序的链表的值。
package com.zqj.SwordOffer;
import java.util.Stack;
/**
* 输入一个链表的头节点,从尾到头反过来打印每个节点的值
*/
public class Interview6 {
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
Stack stack = ReverseList(node1);
while (!stack.empty()){
System.out.print(stack.peek()+"\t");
stack.pop();
}
}
public static Stack ReverseList(Node head){
if(head == null){
System.out.println("链表为空");
}
Stack stack = new Stack();
while(head != null){
stack.push(head.val);
head = head.next;
}
return stack;
}
}
class Node{
int val;
Node next;
public Node(int val){
this.val = val;
}
}
结果展示: