题目描述
输入一个链表的头节点,从尾到头打印链表(用数组返回,不能破环,原有链表的结构)。
示例
输入:head = [1,3,2]
输出:[2,3,1]
/**
* 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<ListNode> stack = new Stack<ListNode>();
ListNode temp= head;
while(temp!=null){
stack.push(temp);
temp = temp.next;
}
int[] result = new int[stack.size()];
int count = 0;
while(!stack.isEmpty()){
result[count++] = stack.pop().val;
}
return result;
}
}
来源:leetcode 剑指offer06