fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define null NULL
  4. struct node
  5. {
  6. int data;
  7. node * next;
  8. };
  9. int main()
  10. {
  11. int n;cin>>n;
  12. int sizee=n;
  13. node * head=null;
  14. node * tail=null;
  15.  
  16. for(int i=0;i<n;i++)
  17. {
  18. int x;cin>>x;
  19. node * newnode=new node;
  20. newnode ->data=x;
  21. newnode ->next=null;
  22. if(head==null)
  23. {
  24. head=newnode;
  25. tail=newnode;
  26. }
  27. else
  28. {
  29. tail->next=newnode;
  30. tail=newnode;
  31. }
  32. }
  33. cout<<"add at end \n";
  34. int x;cin>>x;
  35. node * neww=new node;
  36. neww->data=x;
  37. neww->next=null;
  38. if(head==null)
  39. {
  40. head=neww;
  41. tail = neww;
  42. sizee++;
  43. }
  44. else
  45. {
  46. tail->next=neww;
  47. tail=neww;
  48. sizee++;
  49. }
  50.  
  51. cout<<"add at first\n";
  52. cin>>x;
  53. node * fi=new node;
  54. fi->data=x;
  55. fi->next=head;
  56. head=fi;
  57. sizee++;
  58. node * t=head;
  59. while(t!=null)
  60. {
  61. cout<<t->data<<" ";
  62. t=t->next;
  63. }
  64.  
  65. cout<<"\ndelete from begging \n";
  66. if(head==null)
  67. {
  68. cout<<"\nlinked list is empty\n";
  69. tail=null;
  70. }
  71. else
  72. {
  73. node * p = head;
  74. head=head->next;
  75. delete p;
  76. sizee--;
  77. }
  78. t=head;
  79. while(t!=null)
  80. {
  81. cout<<t->data<<" ";
  82. t=t->next;
  83. }
  84. cout<<"\ndelete from end \n";
  85. if(head==null)
  86. {
  87. cout<< "list empty \n";
  88. tail=null;
  89. }
  90. else
  91. {
  92. node * de=head;
  93. if(head->next==null)
  94. {
  95. head =null;
  96. tail = null;
  97. delete de;
  98. }
  99. else
  100. {
  101. while(de->next->next!= null)
  102. {
  103. de = de->next;
  104. }
  105. node * deleataion = tail ;
  106. de->next=null;
  107. tail = de ;
  108. delete deleataion;
  109. }
  110. sizee--;
  111.  
  112. }
  113. t=head;
  114. while(t!=null)
  115. {
  116. cout<<t->data<<" ";
  117. t=t->next;
  118. }
  119. cout<<"\nsort the liked list \n";
  120.  
  121. for(int i=0;i<sizee-1;i++)
  122. {
  123. node *p=head;
  124. for(int j=0;j<sizee-i-1;j++)
  125. {
  126. if(p->data > p->next->data)
  127. {
  128. swap(p->data,p->next->data);
  129. }
  130. p=p->next;
  131. }
  132. }
  133.  
  134. t=head;
  135. while(t!=null)
  136. {
  137. cout<<t->data<<" ";
  138. t=t->next;
  139. }
  140.  
  141. return 0;
  142. }
Success #stdin #stdout 0.01s 5344KB
stdin
5
2 3 4 52 3
44
42
stdout
add at end 
add at first
42 2 3 4 52 3 44 
delete from begging 
2 3 4 52 3 44 
delete from end 
2 3 4 52 3 
sort the liked list 
2 3 3 4 52