剑指offer练习题 Day02

(1)从尾到头打印链表

import java.util.Stack;
import java.util.ArrayList;
public class Solution {
ArrayList<Integer> arrayList = new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode!=null){
printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}

(2)用两个栈来实现一个队列

 思路分析:

因为栈是先进后出,队是先进先出

双重否定等于肯定

12345->54321->12345

先全部都入1里面,让2出

1的长度不等于0的时候就出1入2

import java.util.Stack;

public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
stack1.push(node);
}

public int pop() {
while(stack2.size()<=0){
while(stack1.size()!=0){
stack2.push(stack1.pop());
}
}

return stack2.pop();
}
}

原文地址:https://www.cnblogs.com/laoduancode/p/12675794.html