Java Program To Delete Nodes Which Have A Greater Value On Right Side
Last Updated :
30 Mar, 2022
Given a singly linked list, remove all the nodes which have a greater value on the right side.
Examples:
Input: 12->15->10->11->5->6->2->3->NULL
Output: 15->11->6->3->NULL
Explanation: 12, 10, 5 and 2 have been deleted because there is a
greater value on the right side. When we examine 12,
we see that after 12 there is one node with a value
greater than 12 (i.e. 15), so we delete 12. When we
examine 15, we find no node after 15 that has a value
greater than 15, so we keep this node. When we go like
this, we get 15->6->3
Input: 10->20->30->40->50->60->NULL
Output: 60->NULL
Explanation: 10, 20, 30, 40, and 50 have been deleted because
they all have a greater value on the right side.
Input: 60->50->40->30->20->10->NULL
Output: No Change.
Method 1 (Simple):
Use two loops. In the outer loop, pick nodes of the linked list one by one. In the inner loop, check if there exists a node whose value is greater than the picked node. If there exists a node whose value is greater, then delete the picked node.
Time Complexity: O(n^2)
Method 2 (Use Reverse):
Thanks to Paras for providing the below algorithm.
1. Reverse the list.
2. Traverse the reversed list. Keep max till now. If the next node is less than max, then delete the next node, otherwise max = next node.
3. Reverse the list again to retain the original order.
Time Complexity: O(n)
Thanks to R.Srinivasan for providing the code below.
Java
// Java program to delete nodes which have
// a greater value on right side
class LinkedList
{
// head of list
Node head;
// Linked list Node
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Deletes nodes which have a node
with greater value node on left side */
void delLesserNodes()
{
// 1.Reverse the linked list
reverseList();
/* 2. In the reversed list, delete nodes
which have a node with greater value
node on left side. Note that head node
is never deleted because it is the
leftmost node.*/
_delLesserNodes();
/* 3. Reverse the linked list again to retain
the original order */
reverseList();
}
/* Deletes nodes which have greater value
node(s) on left side */
void _delLesserNodes()
{
Node current = head;
// Initialise max
Node maxnode = head;
Node temp;
while (current != null &&
current.next != null)
{
/* If current is smaller than max,
then delete current */
if (current.next.data < maxnode.data)
{
temp = current.next;
current.next = temp.next;
temp = null;
}
/* If current is greater than max,
then update max and move current */
else
{
current = current.next;
maxnode = current;
}
}
}
// Utility functions
/* Inserts a new Node at front of
the list. */
void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
// 3. Make next of new Node as head
new_node.next = head;
// 4. Move the head to point to
// new Node
head = new_node;
}
// Function to reverse the linked list
void reverseList()
{
Node current = head;
Node prev = null;
Node next;
while (current != null)
{
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
// Function to print linked list
void printList()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data +
" ");
temp = temp.next;
}
System.out.println();
}
// Driver code
public static void main(String args[])
{
LinkedList llist = new LinkedList();
/* Constructed Linked List is
12->15->10->11->5->6->2->3 */
llist.push(3);
llist.push(2);
llist.push(6);
llist.push(5);
llist.push(11);
llist.push(10);
llist.push(15);
llist.push(12);
System.out.println("Given Linked List");
llist.printList();
llist.delLesserNodes();
System.out.println("Modified Linked List");
llist.printList();
}
}
// This code is contributed by Rajat Mishra
Output:
Given Linked List
12 15 10 11 5 6 2 3
Modified Linked List
15 11 6 3
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 3: The other simpler method is to traverse the list from the start and delete the node when the current Node < next Node. To delete the current node, follow this approach. Let us assume you have to delete current node X:
- Copy next node's data into X i.e X.data = X.next.data.
- Copy next node's next address i.e X.next = X.next.next.
Move forward in the List only when the current Node is > the next Node.
Java
// Java program for above approach
import java.io.*;
// This class represents a single node
// in a linked list
class Node
{
int data;
Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
//This is a utility class for
// linked list
class LLUtil
{
// This function creates a linked list
// from a given array and returns head
public Node createLL(int[] arr)
{
Node head = new Node(arr[0]);
Node temp = head;
Node newNode = null;
for(int i = 1; i < arr.length; i++)
{
newNode = new Node(arr[i]);
temp.next = newNode;
temp = temp.next;
}
return head;
}
// This function prints given
// linked list
public void printLL(Node head)
{
while(head != null)
{
System.out.print(head.data +
" ");
head = head.next;
}
System.out.println();
}
}
// Driver code
class GFG
{
public static void main (String[] args)
{
int[] arr = {12, 15, 10, 11,
5, 6, 2, 3};
LLUtil llu = new LLUtil();
Node head = llu.createLL(arr);
System.out.println("Given Linked List");
llu.printLL(head);
head = deleteNodesOnRightSide(head);
System.out.println("Modified Linked List");
llu.printLL(head);
}
//Main function
public static Node deleteNodesOnRightSide(Node head)
{
if(head == null || head.next == null)
return head;
Node nextNode = deleteNodesOnRightSide(head.next);
if(nextNode.data > head.data)
return nextNode;
head.next = nextNode;
return head;
}
}
Output:
Given Linked List
12 15 10 11 5 6 2 3
Modified Linked List
15 11 6 3
Time Complexity: O(n)
Auxiliary Space: O(1)
Source: https://www.geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-linked-lists-6
Please refer complete article on Delete nodes which have a greater value on right side for more details!
Similar Reads
Java Program For Pointing Arbit Pointer To Greatest Value Right Side Node In A Linked List
Given singly linked list with every node having an additional âarbitraryâ pointer that currently points to NULL. We need to make the âarbitraryâ pointer to the greatest value node in a linked list on its right side. A Simple Solution is to traverse all nodes one by one. For every node, find the node
5 min read
Java Program For Sorting Linked List Which Is Already Sorted On Absolute Values
Given a linked list that is sorted based on absolute values. Sort the list based on actual values.Examples: Input: 1 -> -10 Output: -10 -> 1 Input: 1 -> -2 -> -3 -> 4 -> -5 Output: -5 -> -3 -> -2 -> 1 -> 4 Input: -5 -> -10 Output: -10 -> -5 Input: 5 -> 10 Outpu
4 min read
Java Program To Delete Alternate Nodes Of A Linked List
Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3. Recomm
3 min read
Java Program To Find Next Greater Element
Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the next greater element as -1. Examples: For an array, the righ
6 min read
Java Program to Delete a Node From the Ending of the Circular Linked List
In this article, we will learn about deleting a node from the ending of a circular linked list. Consider the linked list as shown below:Â Example:Input : 5->3->4->(head node)Output: 5->3->(head node)We will first initialize the list and add some data into it with the addNode() method a
3 min read
Java Program For Writing A Function To Delete A Linked List
Algorithm For Java:In Java, automatic garbage collection happens, so deleting a linked list is easy. Just need to change head to null. Implementation: Java // Java program to delete a linked list class LinkedList { // Head of the list Node head; // Linked List node class Node { int data; Node next;
2 min read
Java Program For Pointing To Next Higher Value Node In A Linked List With An Arbitrary Pointer
Given singly linked list with every node having an additional "arbitrary" pointer that currently points to NULL. Need to make the "arbitrary" pointer point to the next higher value node. We strongly recommend to minimize your browser and try this yourself first A Simple Solution is to traverse all n
4 min read
Java Program to Delete a Node From the Middle of the Circular Linked List
In this article, we are going to learn to delete the middle node from the circular Linked List in java. The approach we are going to follow for this program is, first we calculate the number of nodes in the list and then divide the number of nodes by 2 to get the middle node of the list. Algorithm C
4 min read
Java Program For Removing Duplicates From A Sorted Linked List
Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43-
8 min read
Output of Java Programs | Set 55 (Java Collections Framework)
Pre-requisites: Java Collection Framework. 1. What is the Output of following Java Program? Java import java.util.*; class Demo { public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(11); arr.add(2); arr.add(3); arr.add(5); arr.add(7); arr.r
6 min read