fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Node {
  5. int val;
  6. Node* next;
  7. };
  8.  
  9.  
  10. Node* InsertAtBegin(Node* root, int x) {
  11. Node* newnode = new Node();
  12. newnode->val = x;
  13. newnode->next = NULL;
  14. if(root==NULL)
  15. {
  16. root=newnode;
  17. return root;
  18. }
  19. else
  20. {
  21. newnode->next=root;
  22. root=newnode;
  23. return root;
  24. }
  25. }
  26. Node*InsertAtEnd(Node*root,int x)
  27. {
  28. Node*newnode=new Node();
  29. newnode->next=NULL;
  30. newnode->val=x;
  31. if(root==NULL)
  32. {
  33. root=newnode;
  34. return root;
  35. }
  36. Node*currnode;
  37. currnode=root;
  38. while(currnode->next!=NULL)
  39. {
  40. currnode=currnode->next;
  41. }
  42. currnode->next=newnode;
  43. return root;
  44. }
  45.  
  46. void Print(Node* root) {
  47. Node* currnode = root;
  48. while (currnode != NULL) {
  49. cout << currnode->val << " ";
  50. currnode = currnode->next;
  51. }
  52. cout << endl;
  53. }
  54.  
  55. int main() {
  56. Node* root = NULL;
  57. int n;
  58. cin >> n;
  59. if(n<=0)
  60. {
  61. cout<<endl;
  62. return 0;
  63. }
  64. int a[n];
  65. for (int i = 0; i < n; i++) {
  66. cin >> a[i];
  67. }
  68.  
  69. Print(root);
  70. for (int i = 0; i < n; i++) {
  71. root = InsertAtBegin(root, a[i]);
  72. }
  73.  
  74.  
  75. Print(root);
  76. for(int i=0;i<n;i++)
  77. {
  78. root=InsertAtEnd(root,4);
  79. }
  80. Print(root);
  81.  
  82. return 0;
  83. }
Success #stdin #stdout 0.01s 5268KB
stdin
3
7 3 8
stdout
8 3 7 
8 3 7 4 4 4