题目描述:
标签:栈 递归 链表 双指针
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
代码:
思路分析:
定义一个栈(利用先入后出的特性),用来存放链表节点,然后在pop出来存储结果数组中,就能从尾到头输出节点了
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
if(head == null){
return new int[0];
}
Stack<Integer> stack = new Stack<>();
ListNode cur = head;
while(cur != null){
stack.push(cur.val);
cur = cur.next;
}
int[] ans = new int[stack.size()];
int cnt = 0;
while(!stack.isEmpty()){
ans[cnt++] = stack.pop();
}
return ans;
}
}