Topic description
Enter a linked list and print the value of each node in the linked list from end to beginning.
The following methods are only functional and may not be the best. Tested on Niuke.com,
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: #Return the sequence of list values from tail to head, eg [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]