题目地址:
https://www.lintcode.com/problem/reverse-order-storage/description
给定一个链表,将其值逆序存到一个list中返回。
代码如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
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
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
Collections.reverse(list);
return list;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。