从尾到头打印链表
输入一个链表的头节点,从尾到头反过来打印出每个节点的值
具体思路:
解法一:
- 1 .首先想到数据结构是栈,符合后进先出
- 2 . 将节点的值放入Stack中
- 3 .之后将stack中的值pop出来放入ArrayList集合中
- 4 . 返回的集合中的值就是反转后的值
解法二
- 1.递归实现,递归本身就是栈结构
解法一代码
public ArrayList<Integer> printFromTailToHead(ListNode listNode){
ArrayList<Integer> res = new ArrayList<Integer>();
if(listNode==null) {
return res;
}
Stack<Integer> stack = new Stack<Integer>();
while(listNode!=null) {
stack.push(listNode.val);
listNode = listNode.next;
}
while(!stack.isEmpty()) {
res.add(stack.pop());
}
return res;
}
解法二代码:
public static void printFromTailToHead(ListNode listNode){
//递归实现
if(listNode!=null) {
if(listNode.next!=null) {
printFromTailToHead(listNode.next);
}
System.out.println(listNode.val);
}
}