- Reverse Order Storage
中文English
Give a linked list, and store the values of linked list in reverse order into an array.
Example
Example1
Input: 1 -> 2 -> 3 -> null
Output: [3,2,1]
Example2
Input: 4 -> 2 -> 1 -> null
Output: [1,2,4]
Notice
You can not change the structure of the original linked list.
ListNode have two elements: ListNode.val and ListNode.next
解法1:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: the given linked list
* @return: the array that store the values in reverse order
*/
vector<int> reverseStore(ListNode * head) {
if (!head) return vector<int>();
vector<int> result;
while(head) {
result.push_back(head->val);
head = head->next;
}
reverse(result.begin(), result.end());
return result;
}
};
解法2:网上的做法。我觉得很好。
class Solution {
public:
/**
* @param head: the given linked list
* @return: the array that store the values in reverse order
*/
vector<int> reverseStore(ListNode * head) {
vector<int> result;
helper(head, result);
return result;
}
private:
void helper(ListNode * head, vector<int> & result) {
if (!head) return;
helper(head->next, result);
result.push_back(head->val);
}
};