/**
* 题 面试题 5 : 从尾到头打印链表
题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
* */
class ListNode{
int val;
ListNode next;
}
public class Test05 {
//后进先出:使用栈进行操作
public void printFromEnd(ListNode head){
if (head==null) {
return;
}
ListNode nextNode=head;
Stack<Integer>stack=new Stack<>();
while(nextNode!=null){
stack.add(nextNode.val);
nextNode=nextNode.next;
}
while(stack.size()>0){
System.out.println(stack.pop());
}
}
//递归的方式实现
public void printFromReverse(ListNode head){
if (head==null) {
return;
}
if(head.next!=null){
printFromReverse(head.next);
}
System.out.println(head.val);
}
public static void main(String[] args) {
ListNode node1=new ListNode();
ListNode node2=new ListNode();
ListNode node3=new ListNode();
node1.val=1;
node2.val=2;
node3.val=3;
node1.next=node2;
node2.next=node3;
Test05 test=new Test05();
// test.printFromEnd(node1);
test.printFromReverse(node1);
}
}
/**
* 题 面试题 5 : 从尾到头打印链表
题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
* */
class ListNode{
int val;
ListNode next;
}
public class Test05 {
//后进先出:使用栈进行操作
public void printFromEnd(ListNode head){
if (head==null) {
return;
}
ListNode nextNode=head;
Stack<Integer>stack=new Stack<>();
while(nextNode!=null){
stack.add(nextNode.val);
nextNode=nextNode.next;
}
while(stack.size()>0){
System.out.println(stack.pop());
}
}
//递归的方式实现
public void printFromReverse(ListNode head){
if (head==null) {
return;
}
if(head.next!=null){
printFromReverse(head.next);
}
System.out.println(head.val);
}
public static void main(String[] args) {
ListNode node1=new ListNode();
ListNode node2=new ListNode();
ListNode node3=new ListNode();
node1.val=1;
node2.val=2;
node3.val=3;
node1.next=node2;
node2.next=node3;
Test05 test=new Test05();
// test.printFromEnd(node1);
test.printFromReverse(node1);
}
}