fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct SinglyLinkedListNode {
  5. int data;
  6. SinglyLinkedListNode* next;
  7. SinglyLinkedListNode(int value) : data(value), next(nullptr) {}
  8. };
  9.  
  10. SinglyLinkedListNode* removeNodes(SinglyLinkedListNode* listHead, int x) {
  11. // Dummy node to simplify edge cases (e.g., head node removal)
  12. SinglyLinkedListNode* dummy = new SinglyLinkedListNode(0);
  13. dummy->next = listHead;
  14.  
  15. SinglyLinkedListNode* current = dummy;
  16. while (current->next != nullptr) {
  17. if (current->next->data > x) {
  18. // Node to be removed
  19. SinglyLinkedListNode* temp = current->next;
  20. current->next = current->next->next;
  21. delete temp; // Free memory
  22. } else {
  23. current = current->next;
  24. }
  25. }
  26.  
  27. SinglyLinkedListNode* newHead = dummy->next;
  28. delete dummy; // Free dummy node
  29. return newHead;
  30. }
  31.  
  32. // Helper function to print the linked list
  33. void printList(SinglyLinkedListNode* head) {
  34. while (head) {
  35. cout << head->data << " ";
  36. head = head->next;
  37. }
  38. cout << endl;
  39. }
  40.  
  41. int main() {
  42. // Example usage:
  43. SinglyLinkedListNode* head = new SinglyLinkedListNode(5);
  44. head->next = new SinglyLinkedListNode(2);
  45. head->next->next = new SinglyLinkedListNode(3);
  46. head->next->next->next = new SinglyLinkedListNode(4);
  47. head->next->next->next->next = new SinglyLinkedListNode(5);
  48.  
  49. int x = 3;
  50. SinglyLinkedListNode* result = removeNodes(head, x);
  51. printList(result); // Expected output: 2 3
  52.  
  53. // Free remaining nodes
  54. while (result != nullptr) {
  55. SinglyLinkedListNode* temp = result;
  56. result = result->next;
  57. delete temp;
  58. }
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
2 3