题目
倒序打印链表
题解
- 递归
int size = 0;
int index = 0;
int [] data;
public int[] printDesc(ListNode root) {
visit(root);
return data;
}
private void visit(ListNode root){
if(root==null){
data = new int[size];
return;
}
size++;
visit(root.getNext());
data[index++] = root.getValue();
}
- 非递归方式 我们使用栈即可
public int[] printDescByStack(ListNode root) {
Deque<Integer> stack = new LinkedList<>();
while (root != null) {
stack.push(root.getValue());
root = root.getNext();
}
int []res = new int[stack.size()];
int index = 0;
while (!stack.isEmpty()){
res[index++]=stack.pop();
}
return res;
}
源码: 剑指offer4J
网友评论