fork(3) download
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. using namespace std;
  5.  
  6. struct node
  7. {
  8. int data;
  9. struct node* next;
  10. };
  11.  
  12. void push(struct node** head_ref, int new_val)
  13. {
  14. struct node* new_node = (struct node*)malloc(sizeof(struct node));
  15. new_node->data = new_val;
  16. new_node->next = (*head_ref);
  17. (*head_ref) = new_node;
  18. }
  19.  
  20. void print_list(struct node* head)
  21. {
  22. while(head!=NULL)
  23. {
  24. cout<< head->data <<"->";
  25. head = head->next;
  26. }
  27. cout<<"NULL";
  28. cout<<endl;
  29. }
  30.  
  31. void remove_lower(struct node** head_ref)
  32. {
  33. struct node* current = (*head_ref);
  34. if(current == NULL || current->next == NULL)
  35. return ;
  36.  
  37. struct node* prev = NULL, *next = NULL, *temp = NULL;
  38. while(current->next != NULL)
  39. {
  40. next = current->next;
  41. temp = next;
  42. /*
  43.   * check if there is any element greater than current
  44.   * in the remaining list.
  45.   */
  46.  
  47. while(temp->next != NULL) {
  48. if (temp->data > current->data) {
  49. /*
  50.   * if some element is greater than current, then
  51.   * delete current element.
  52.   */
  53. free(current);
  54. current = NULL;
  55. if (prev == NULL) {
  56. /* it was the first element, need to update the head */
  57. *head_ref = next;
  58. } else {
  59. /* not first element - update "prev->next" pointer */
  60. prev->next = next;
  61. }
  62. break;
  63. }
  64. temp = temp->next;
  65. }
  66. /* if current element was not deleted - update "prev" pointer */
  67. if (current != NULL) {
  68. prev = current;
  69. }
  70. current = next;
  71. }
  72. }
  73.  
  74. int main()
  75. {
  76. struct node* head = NULL;
  77. for(int i = 0; i <= 7; i++)
  78. {
  79. push(&head,i);
  80. if(i%2==0)
  81. push(&head,i*i);
  82. push(&head,i-5);
  83. }
  84. print_list(head);
  85. remove_lower(&head);
  86. print_list(head);
  87. return 0;
  88. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
2->7->1->36->6->0->5->-1->16->4->-2->3->-3->4->2->-4->1->-5->0->0->NULL
36->16->4->4->2->1->0->0->NULL