Given a linked list, the problem is to delete all the nodes from the list that are greater than the specified value x.
Examples:
Input : list: 7->3->4->8->5->1
x = 6
Output : 3->4->5->1
Input : list: 1->8->7->3->7->10
x = 7
Output : 1->7->3->7
We need to first check for all occurrences at head node which are greater than ‘x’, delete them and change the head node appropriately. Then we need to check for all occurrences inside a loop and delete them one by one.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* getNode( int data)
{
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void deleteGreaterNodes(Node** head_ref, int x)
{
Node *temp = *head_ref, *prev;
if (temp != NULL && temp->data > x) {
*head_ref = temp->next;
free (temp);
temp = *head_ref;
}
while (temp != NULL) {
while (temp != NULL && temp->data <= x) {
prev = temp;
temp = temp->next;
}
if (temp == NULL)
return ;
prev->next = temp->next;
delete temp;
temp = prev->next;
}
}
void printList(Node* head)
{
while (head) {
cout << head->data << " " ;
head = head->next;
}
}
int main()
{
Node* head = getNode(7);
head->next = getNode(3);
head->next->next = getNode(4);
head->next->next->next = getNode(8);
head->next->next->next->next = getNode(5);
head->next->next->next->next->next = getNode(1);
int x = 6;
cout << "Original List: " ;
printList(head);
deleteGreaterNodes(&head, x);
cout << "\nModified List: " ;
printList(head);
return 0;
}
|
Output:
Original List: 7 3 4 8 5 1
Modified List: 3 4 5 1
Time Complexity: O(n).
Comments
Post a Comment