fork download
  1. // #include <bits/stdc++.h>
  2. #include<iostream>
  3. #include<algorithm>
  4. using namespace std;
  5. /*
  6.  
  7. */
  8. struct node{
  9. int data ;
  10. node *nxt;
  11.  
  12. node(int d , node*n=0){
  13. data = d;
  14. nxt = n;
  15. }
  16. };
  17.  
  18. class list{
  19. node *head , *tail;
  20.  
  21. public :
  22. list();
  23. void add_end(int el);
  24. bool is_empty();
  25. void del_pos(int pos);
  26. int size();
  27. void deleteNodesGreaterThan(int el);
  28. void print();
  29.  
  30.  
  31.  
  32. };
  33. void list::print(){
  34. node *t = head;
  35. while(t!=0){
  36. cout<<t->data<<" ";
  37. t =t->nxt;
  38. }
  39. cout<<endl;
  40. }
  41. void list::deleteNodesGreaterThan(int el){
  42. int i = 1;
  43. node *tmp = head;
  44. while(tmp != 0){
  45. if(tmp->data > el){
  46. del_pos(i);
  47. }
  48. else {
  49. i++;
  50. tmp = tmp->nxt; // Move to the next node only when not deleting
  51. }
  52. }
  53. }
  54.  
  55. int list::size(){
  56. int c=0;
  57. node *tmp=head;
  58. while(tmp!=0){
  59. c++;
  60. tmp = tmp->nxt;
  61. }
  62. return c;
  63. }
  64. list::list(){
  65. head = tail = 0;
  66. }
  67. bool list::is_empty(){
  68. return head==0;
  69. }
  70. void list::add_end(int el){
  71. if(is_empty()){
  72. head = tail= new node(el);
  73. }
  74. else {
  75. tail->nxt= new node(el);
  76. tail = tail->nxt;
  77. }
  78.  
  79.  
  80. }
  81. void list::del_pos(int pos){
  82. if(size()==1){
  83. delete head;
  84. head = tail = 0;
  85. }
  86. else if(pos==1){
  87. node *tmp = head;
  88. head = head->nxt;
  89. delete tmp;
  90. }
  91. else if(pos==size()){
  92. node *tmp = head;
  93. int i =0;
  94. while(tmp->nxt!=tail){
  95. tmp = tmp->nxt;
  96. }
  97. delete tail;
  98. tail = tmp;
  99. tail->nxt =0;
  100. }
  101. else {
  102. node *t1 = head , *t2 , *t3;
  103. for(int i =1;i<pos-1;i++){
  104. t1=t1->nxt;
  105. }
  106. t2= t1->nxt;
  107. t3=t2->nxt;
  108. delete t2;
  109. t1->nxt = t3;
  110. }
  111.  
  112.  
  113. }
  114.  
  115. int main() {
  116. list l;
  117. l.add_end(10);
  118. l.add_end(5);
  119. l.add_end(-10);
  120. l.add_end(3);
  121. l.add_end(4);
  122. l.add_end(0);
  123. l.add_end(9);
  124. l.print();
  125. l.deleteNodesGreaterThan(5);
  126. l.print();
  127. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
10 5 -10 3 4 0 9 
5 -10 3 4 0 9