题目描述
输入一个链表,从尾到头打印链表每个节点的值。
以下方法仅仅实现了功能,未必最佳。在牛客网测试,
C++:3ms 480k
Python:23ms 5732k
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> vec_output; if (head == NULL){return vec_output;} do{ vec_output.push_back(head->val); head = head->next; }while(head!=NULL); reverse(vec_output.begin(),vec_output.end()); return vec_output; } };
Python:
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): list_val = [] while(True): if listNode == None: return [] list_val.append(listNode.val) if (listNode.next): listNode = listNode.next else: break return list_val[::-1]