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