1.从尾到头打印单链表
利用栈先遍历一遍链表,然后依次从栈顶弹出即可。
public static void printList(ListNode head){
Stack<Integer> s = new Stack<>();
ListNode node = head;
while(node!=null){
s.push(node.val);
node = node.next;
}
while(!s.isEmpty()){
System.out.println(s.pop());
}
}
利用递归方式 当head非空以及head,next非空说明head为最后一个元素,则输出,否则递归调用
public static void printListRec(ListNode head){
if(head != null){
if(head.next == null){
System.out.println(head.val);
}else{
printListRec(head.next);
}
}
}