Lintcode822. 相反的顺序存储

描述

给出一个链表,并将链表的值以倒序存储到数组中。

  • 您不能改变原始链表的结构。
  • ListNode 有两个成员变量:ListNode.val 和 ListNode.next

样例
样例1

输入: 1 -> 2 -> 3 -> null
输出: [3,2,1]

样例2

输入: 4 -> 2 -> 1 -> null
输出: [1,2,4]

把链表数据存到vector里面
之后reverse
返回
就可以了


/**
 * 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) {
        // write your code here
        vector<int> aa;
        for(int i=0;head!=NULL;i++){
            aa.push_back(head->val);
            head = head->next;
        }
        reverse(aa.begin(),aa.end());
        return aa;
    }
};

你可能感兴趣的:(lintcode)