#include <bits/stdc++.h>
using namespace std;
struct SinglyLinkedListNode {
int data;
SinglyLinkedListNode* next;
SinglyLinkedListNode(int value) : data(value), next(nullptr) {}
};
SinglyLinkedListNode* removeNodes(SinglyLinkedListNode* listHead, int x) {
// Dummy node to simplify edge cases (e.g., head node removal)
SinglyLinkedListNode* dummy = new SinglyLinkedListNode(0);
dummy->next = listHead;
SinglyLinkedListNode* current = dummy;
while (current->next != nullptr) {
if (current->next->data > x) {
// Node to be removed
SinglyLinkedListNode* temp = current->next;
current->next = current->next->next;
delete temp; // Free memory
} else {
current = current->next;
}
}
SinglyLinkedListNode* newHead = dummy->next;
delete dummy; // Free dummy node
return newHead;
}
// Helper function to print the linked list
void printList(SinglyLinkedListNode* head) {
while (head) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
int main() {
// Example usage:
SinglyLinkedListNode* head = new SinglyLinkedListNode(5);
head->next = new SinglyLinkedListNode(2);
head->next->next = new SinglyLinkedListNode(3);
head->next->next->next = new SinglyLinkedListNode(4);
head->next->next->next->next = new SinglyLinkedListNode(5);
int x = 3;
SinglyLinkedListNode* result = removeNodes(head, x);
printList(result); // Expected output: 2 3
// Free remaining nodes
while (result != nullptr) {
SinglyLinkedListNode* temp = result;
result = result->next;
delete temp;
}
return 0;
}