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. Node*InsertAtEnd(Node*root,int x)
  47. {
  48. Node*newnode;
  49. newnode->next=NULL;
  50. newnode->val=x;
  51. if(root==NULL)
  52. {
  53. root=newnode;
  54. return root;
  55. }
  56. Node*currnode;
  57. currnode=root;
  58. while(currnode->next!=NULL)
  59. {
  60. currnode=currnode->next;
  61. }
  62. currnode->next=newnode;
  63. return root;
  64. }
  65. Node*SortedInsert(Node*root,int x)
  66. {
  67. Node*newnode=new Node();
  68. newnode->next=NULL;
  69. newnode->val=x;
  70. Node*currnode,*prevnode;
  71. currnode=root;
  72. prevnode=NULL;
  73. if(root==NULL)
  74. {
  75. root=newnode;
  76. return root;
  77. }
  78. if(x<root->val)
  79. {
  80. newnode->next=root;
  81. root=newnode;
  82. return root;
  83. }
  84. while(currnode!=NULL)
  85. {
  86. if(currnode->val<x)
  87. {
  88. prevnode=currnode;
  89. currnode=currnode->next;
  90. }
  91. else
  92. {
  93. prevnode->next=newnode;
  94. newnode->next=currnode;
  95. return root;
  96. }
  97. }
  98. prevnode->next=newnode;
  99. newnode->next=NULL;
  100. return root;
  101. }
  102. void Print(Node*root)
  103. {
  104. Node*currnode;
  105. currnode=root;
  106. while(currnode!=NULL)
  107. {
  108. cout<<currnode->val<<" ";
  109. currnode=currnode->next;
  110. }
  111. cout<<endl;
  112. }
  113. int main()
  114. {
  115. Node*root=NULL;
  116. root=InsertAtBegin(root,3);
  117. root=InsertAtBegin(root,1);
  118. root=InsertAtBegin(root,9);
  119. Print(root);
  120. root=InsertAtPos(root,2,0);
  121. root=InsertAtPos(root,8,2);
  122. Print(root);
  123. root=InsertAtEnd(root,7);
  124. Print(root);
  125. root=InsertAtEnd(root,5);
  126. Print(root);
  127. root=SortedInsert(root,6);
  128. root=SortedInsert(root,0);
  129. Print(root);
  130. }
  131.  
  132.  
Success #stdin #stdout 0.01s 5268KB
stdin
Standard input is empty
stdout
9 1 3 
2 9 8 1 3 
2 9 8 1 3 
2 9 8 1 3 
0 2 6 9 8 1 3