fork download
  1. #include <stdio.h>
  2.  
  3. struct Node
  4. {
  5. Node(int value)
  6. : m_value(value)
  7. , next(NULL)
  8. {}
  9.  
  10. int m_value;
  11. struct Node * next;
  12. };
  13.  
  14. Node* reverse_list1( Node* list )
  15. {
  16. if( list == NULL) return NULL; // reverse of empty list is empty list.
  17. if( list->next == NULL ) // last element in list?
  18. return list; // the reverse of a list with 1 element is the same.
  19. else
  20. {
  21. Node* head = list;
  22. Node* tail = list->next;
  23. head->next = NULL;
  24. Node* end_of_reverse_tail = tail; // the first will be the last...
  25. Node * result = reverse_list1(tail);
  26. end_of_reverse_tail->next = head;
  27. return result;
  28. }
  29. }
  30.  
  31. int main(void) {
  32. Node *a[3] = { new Node(0), new Node(1), new Node(2) };
  33. a[0]->next = a[1];
  34. a[1]->next = a[2];
  35. a[2]->next = NULL;
  36. Node * reversed = reverse_list1(a[0]);
  37. for( Node* current = reversed; current != NULL; current = current->next)
  38. printf("%d\n",current->m_value);
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
2
1
0