从尾到头打印链表
描述
输入一个链表的头结点,从头到尾反过来打印每个节点的值。
方法
- 递归
- 非递归
代码
1.递归
package chapter2;
import structure.ListNode;
import java.util.Stack;
/*
从尾到头打印链表
*/
public class PrintListInReversedOrder {
//递归版
public static void printReversinglyRecursively(ListNode<Integer> node){
if(node==null)
return;
else{
printReversinglyRecursively(node.next);
System.out.println(node.val);
}
}
public static void main(String[] args){
ListNode<Integer> head = new ListNode<Integer>(1);
head.next = new ListNode<Integer>(2);
head.next.next = new ListNode<Integer>(3);
printReversinglyRecursively(head);
System.out.println();
printReversinglyIteratively(head);
}
}
2.非递归
package chapter2;
import structure.ListNode;
import java.util.Stack;
/*
从尾到头打印链表
*/
public class PrintListInReversedOrder {
//非递归版
public static void printReversinglyIteratively(ListNode<Integer> node){
Stack<Integer> stack = new Stack<>();
for(ListNode<Integer> temp=node;temp!=null;temp=temp.next)
stack.add(temp.val);
while(!stack.isEmpty())
System.out.println(stack.pop());
}
public static void main(String[] args){
ListNode<Integer> head = new ListNode<Integer>(1);
head.next = new ListNode<Integer>(2);
head.next.next = new ListNode<Integer>(3);
printReversinglyRecursively(head);
System.out.println();
printReversinglyIteratively(head);
}
}