從尾到頭打印鏈表(JS和C++版本)

題目描述

輸入一個鏈表,按鏈表值從尾到頭的順序返回一個ArrayList。

C++

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> v;
            while(head != NULL){
                v.insert(v.begin(),head->val);
                head = head->next;
            }
            return v;
    }
};

JS

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function printListFromTailToHead(head)
{
    // write code here
    let arr = [];
    while(head !== null){
        arr.unshift(head.val);
        head = head.next;
    }
    return arr;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章