输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。
如输入{1,2,3}的链表如下图:
返回一个数组为[3,2,1]
0 <= 链表长度 <= 10000
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function printListFromTailToHead(head)
{
// write code here
let array1 = [];
while(head) {
// 将获取的值push进新数组
array1.push(head.val);
// 更新head值
head = head.next
}
// 使用数组的反转方法
return array1.reverse()
}
module.exports = {
printListFromTailToHead : printListFromTailToHead
};
function printListFromTailToHead (head) {
let arr = [];
while (head != null) {
arr.unshift(head.val)
head = head.next;
}
return arr;
}
//TS 递归版
export function printListFromTailToHead(head: ListNode,res = []): number[] {
if(head){
printListFromTailToHead(head.next,res)
res.push(head.val)
}
return res
}
function printListFromTailToHead(head)
{
// write code here
var res = [];
while(head){
res.unshift(head.val);
head = head.next;
}
return res;
} function printListFromTailToHead(head)
{
// write code here
let p = head, arry = [];
while(p) {
arry.unshift(p.val);
p = p.next;
}
return arry;
} /*function ListNode(x){
this.val = x;
this.next = null;
}*/
function printListFromTailToHead(head) {
var ansArrList = [];
function reCur(head) {
if (head != null) {
reCur(head.next);
ansArrList.push(head.val);
}
return ansArrList
}
return reCur(head)
} /*function ListNode(x){
this.val = x;
this.next = null;
}*/
/**
* 我的解题思路:
* 先生成正序的数组,然后再逆序一下就好了
*
* @param {*} head
*/
function printListFromTailToHead(head)
{
// write code here
const result = [];
let nextNode = head;
while (nextNode) {
result.push(nextNode.val);
nextNode = nextNode.next;
}
return result.reverse();
}
/**
* 社区TOP1解答思路:
* 使用递归来解决时间复杂度的问题,一行搞定
*
* @param {*} head
*/
function topPrintListFromTailToHead(head)
{
// write code here
return head ? topPrintListFromTailToHead(head.next).length ? [...topPrintListFromTailToHead(head.next), head.val] : [head.val] : [];
}
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(struct ListNode* head) { vector<int> value; if(head != NULL) { value.insert(value.begin(),head->val); if(head->next != NULL) { vector<int> tempVec = printListFromTailToHead(head->next); if(tempVec.size()>0) value.insert(value.begin(),tempVec.begin(),tempVec.end()); } } return value; } };/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(struct ListNode* head) { vector<int> value; if(head != NULL) { value.insert(value.begin(),head->val); while(head->next != NULL) { value.insert(value.begin(),head->next->val); head = head->next; } } return value; } };