描述
给出一个链表,并将链表的值以倒序存储到数组中。
样例
样例1
输入: 1 -> 2 -> 3 -> null
输出: [3,2,1]
样例2
输入: 4 -> 2 -> 1 -> null
输出: [1,2,4]
注意事项
- 您不能改变原始链表的结构。
- ListNode 有两个成员变量:ListNode.val 和 ListNode.next
代码部分
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: the given linked list
* @return: the array that store the values in reverse order
*/
public List<Integer> reverseStore(ListNode head) {
// write your code here
Stack stack=new Stack();
List list=new ArrayList();
if(head==null)return list;
while(head!=null){
stack.push(head.val);
head=head.next;
}
while(!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
}