Title Description Enter a list of values for each node of the list to print from the end of the header. The following methods only implement the function, not necessarily the best. In the cattle-guest network test, C++:3MS 480kpython:23ms 5732k
/** * struct ListNode {* int val;* struct ListNode *next;* listnode (int x):* val (x), Next (NULL) {*}*};*/classSolution { Public: Vector<int> Printlistfromtailtohead (listnode*head) {Vector<int>Vec_output; if(head = = NULL) {returnVec_output;} Do{vec_output.push_back (head-val); Head= head->Next; } while(head!=NULL); Reverse (Vec_output.begin (), Vec_output.end ()); returnVec_output; }};
Python:
#-*-coding:utf-8-*-#class ListNode:#def __init__ (self, x):#self.val = x#Self.next = NoneclassSolution:#returns a sequence of list values from the tail to the head, for example [ . defPrintlistfromtailtohead (Self, ListNode): List_val= [] while(True):ifListNode = = None:return[] List_val.append (Listnode.val)if(listnode.next): ListNode=Listnode.nextElse: Break returnLIST_VAL[::-1]
"Algorithmic programming C + + Python" single-linked list reverse output