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. Node*InsertAtPos(Node*root,int x,int pos)
  46. {
  47. if(pos==0)
  48. {
  49. root=InsertAtBegin(root,x);
  50. }
  51. else
  52. {
  53. Node*newnode=new Node();
  54. newnode->val=x;
  55. newnode->next=NULL;
  56. Node*currnode;
  57. currnode=root;
  58. for(int i=1;i<pos;i++)
  59. {
  60. currnode=currnode->next;
  61. }
  62. newnode->next=currnode->next;
  63. currnode->next=newnode;
  64. }
  65. return root;
  66. }
  67. void Print(Node* root) {
  68. Node* currnode = root;
  69. while (currnode != NULL) {
  70. cout << currnode->val << " ";
  71. currnode = currnode->next;
  72. }
  73. cout << endl;
  74. }
  75.  
  76. int main() {
  77. Node* root = NULL;
  78. int n;
  79. cin >> n;
  80. if(n<=0)
  81. {
  82. cout<<endl;
  83. return 0;
  84. }
  85. int a[n];
  86. for (int i = 0; i < n; i++) {
  87. cin >> a[i];
  88. }
  89.  
  90. Print(root);
  91. for (int i = 0; i < n; i++) {
  92. root = InsertAtBegin(root, a[i]);
  93. }
  94.  
  95.  
  96. Print(root);
  97. for(int i=0;i<n;i++)
  98. {
  99. root=InsertAtEnd(root,4);
  100. }
  101. Print(root);
  102. for(int i=0;i<n;i++)
  103. {
  104. root=InsertAtPos(root,5,0);
  105. root=InsertAtPos(root,8,3);
  106. }
  107. Print(root);
  108. return 0;
  109. }
Success #stdin #stdout 0.01s 5284KB
stdin
3
7 3 8
stdout
8 3 7 
8 3 7 4 4 4 
5 5 5 8 8 8 3 8 7 4 4 4