思路:可以用stack或者vector做buffer, stack的default implementation是deque,对于本题来说有些浪费,只要用array-based vector然后倒着读就行了。如果不让用额外空间,那只能O(n^2)递归了。
- void printlist(ListNode *head){
- vector<int> v;
- while(head){
- v.push_back(val);
- head = head->next;
- }
- for(int i = v.size() - 1; i >=0; i--){
- cout<<v[i]<<" ";
- }
- }
- void printlist(ListNode *head){
- if(!head) return;
- printlist(head->next);
- cout<<" "<<head->val;
- }
No comments:
Post a Comment