fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Node {
  6. int data;
  7. Node *next;
  8. };
  9.  
  10. void append_node(Node **, int);
  11. void list(Node *);
  12.  
  13. int main(void) {
  14. int i, n, x;
  15. Node *head = NULL;
  16.  
  17. cin >> n;
  18. for (i = 0; i < n; i++) {
  19. cin >> x;
  20. append_node(&head, x);
  21. }
  22.  
  23. list(head);
  24. return 0;
  25. }
  26.  
  27. void append_node(Node **cur, int x) {
  28. Node *new_node = new Node;
  29. new_node->data = x;
  30. new_node->next = NULL;
  31.  
  32. if (*cur == NULL) {
  33. *cur = new_node;
  34. return;
  35. }
  36.  
  37. new_node->next = (*cur)->next;
  38. (*cur)->next = new_node;
  39. }
  40.  
  41. void list(Node *cur) {
  42. if (cur == NULL) return;
  43.  
  44. while (cur != NULL) {
  45. cout << cur->data << " ";
  46. cur = cur->next;
  47. }
  48.  
  49. cout << endl;
  50. }
Success #stdin #stdout 0.01s 2860KB
stdin
5
1 2 3 4 5
stdout
1 5 4 3 2