Search code examples
algorithmlinked-list

Deleting nodes greater than specified value from linked list


Given an integer value and a pointer to the head of the linked list, how to delete all the nodes from the list that are greater than the specified value?

e.g.

List : 10->34->11->19->26->55->17 value: 19 output: 10->11->17 (All the nodes greater than 19 needs to be removed)

(Edge case)

List : 10->3->17->5->2->14->7 value: 9 output: 3->5->2->7 (All the nodes greater than 9 needs to be removed)

I am not looking for the exact code but just an algorithm to solve this!


Solution

  • enter image description here Consider the picture here .Suppose we have to delete the node which is greater than 8 and we have Head Pointer pointing to head of the list.First we will take two pointers Prev and temp both points to head initially.Then through the pointer we will traverse the list and keep track the current and prev pointers in temp and Prev.If current number is greater than 8 Prev will point to the next node pointed by temp and temp node will be deleted.By traversing all the node and following this rule you can delete the specified node of the list.... I hope you got the point........