Wednesday, May 15, 2013

Print linked list in reverse order C++

Print a linked list recursively in a reverse manner without changing the actual list

思路:可以用stack或者vector做buffer, stack的default implementation是deque,对于本题来说有些浪费,只要用array-based vector然后倒着读就行了。如果不让用额外空间,那只能O(n^2)递归了。


  1. void printlist(ListNode *head){  
  2.   
  3.  vector<int> v;  
  4.   
  5.  while(head){  
  6.   
  7.       v.push_back(val);  
  8.   
  9.       head = head->next;  
  10.   
  11.  }  
  12.   
  13.  for(int i = v.size() - 1; i >=0; i--){  
  14.   
  15.   cout<<v[i]<<" ";  
  16.   
  17. }  
  18. }   
递归:
  1. void printlist(ListNode *head){  
  2.   if(!head) return;  
  3.   printlist(head->next);  
  4.   cout<<" "<<head->val;  
  5. }   

No comments:

Post a Comment