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