fork download
  1. #include <iostream>
  2.  
  3. struct Node{
  4. Node(): next(NULL){}
  5. Node *next;
  6. std::string data;
  7. };
  8.  
  9. void printlist(Node* l){
  10. while(l){
  11. std::cout<<l->data<<std::endl;
  12. l = l->next;
  13. }
  14. std::cout<<"----"<<std::endl;
  15. }
  16.  
  17. void reverse(Node*& l)
  18. {
  19. Node* prev = NULL;
  20. while(l){
  21. auto next = l->next;
  22. l->next = prev;
  23. prev=l;
  24. l=next;
  25. }
  26. l = prev;
  27. }
  28.  
  29. int main() {
  30. Node s,t,u,v;
  31. s.data = "1";
  32. t.data = "2";
  33. u.data = "3";
  34. v.data = "4";
  35. s.next = &t;
  36. t.next = &u;
  37. u.next = &v;
  38. Node* ptr = &s;
  39. printlist(ptr);
  40. reverse(ptr);
  41. printlist(ptr);
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
1
2
3
4
----
4
3
2
1
----