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