输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
题目描述了一个先进后出的结构,很容易想到栈,
进而想到递归,递归也可以实现先进后出,只要将本节点的操作置于递归之后即可。
栈:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> s=new Stack<Integer>();
while(head!=null){
s.push(head.val);
head=head.next;
}
int size=s.size();
int[] a=new int[size];
for(int i=0;i<size;i++){
a[i]=s.pop();
}
return a;
}
}
递归:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ArrayList<Integer> array=new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
addResult(head);
int size=array.size();
int[] a=new int[size];
for(int i=0;i<size;i++){
a[i]=array.get(i);
}
return a;
}
public void addResult(ListNode head){
if(head!=null){
if(head.next!=null){
addResult(head.next);
}
array.add(head.val);
}
}
}