Given a singly linked list, remove all the nodes which have a greater value on the right side.
Examples:
a) The list 12->15->10->11->5->6->2->3->NULL should be changed to 15->11->6->3->NULL. Note that 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->11->6->3->NULL
b) The list 10->20->30->40->50->60->NULL should be changed to 60->NULL. Note that 10, 20, 30, 40, and 50 have been deleted because they all have a greater value on the right side.
c) The list 60->50->40->30->20->10->NULL should not be changed.
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)
Auxiliary Space: O(1)
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.
Thanks to R.Srinivasan for providing the code below.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* next;
};
void reverseList( struct Node** headref);
void _delLesserNodes( struct Node* head);
void delLesserNodes( struct Node** head_ref)
{
reverseList(head_ref);
_delLesserNodes(*head_ref);
reverseList(head_ref);
}
void _delLesserNodes( struct Node* head)
{
struct Node* current = head;
struct Node* maxnode = head;
struct Node* temp;
while (current != NULL &&
current->next != NULL)
{
if (current->next->data < maxnode->data)
{
temp = current->next;
current->next = temp->next;
free (temp);
}
else
{
current = current->next;
maxnode = current;
}
}
}
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node = ( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
void reverseList( struct Node** headref)
{
struct Node* current = *headref;
struct Node* prev = NULL;
struct Node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*headref = prev;
}
void printList( struct Node* head)
{
while (head != NULL)
{
cout << " " << head->data ;
head = head->next;
}
cout << "\n" ;
}
int main()
{
struct Node* head = NULL;
push(&head, 3);
push(&head, 2);
push(&head, 6);
push(&head, 5);
push(&head, 11);
push(&head, 10);
push(&head, 15);
push(&head, 12);
cout << "Given Linked List \n" ;
printList(head);
delLesserNodes(&head);
cout << "Modified Linked List \n" ;
printList(head);
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void reverseList( struct Node** headref);
void _delLesserNodes( struct Node* head);
void delLesserNodes( struct Node** head_ref)
{
reverseList(head_ref);
_delLesserNodes(*head_ref);
reverseList(head_ref);
}
void _delLesserNodes( struct Node* head)
{
struct Node* current = head;
struct Node* maxnode = head;
struct Node* temp;
while (current != NULL && current->next != NULL) {
if (current->next->data < maxnode->data) {
temp = current->next;
current->next = temp->next;
free (temp);
}
else {
current = current->next;
maxnode = current;
}
}
}
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node = ( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
void reverseList( struct Node** headref)
{
struct Node* current = *headref;
struct Node* prev = NULL;
struct Node* next;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*headref = prev;
}
void printList( struct Node* head)
{
while (head != NULL) {
printf ( "%d " , head->data);
head = head->next;
}
printf ( "\n" );
}
int main()
{
struct Node* head = NULL;
push(&head, 3);
push(&head, 2);
push(&head, 6);
push(&head, 5);
push(&head, 11);
push(&head, 10);
push(&head, 15);
push(&head, 12);
printf ( "Given Linked List \n" );
printList(head);
delLesserNodes(&head);
printf ( "Modified Linked List \n" );
printList(head);
return 0;
}
|
Java
class LinkedList {
Node head;
class Node {
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
void delLesserNodes()
{
reverseList();
_delLesserNodes();
reverseList();
}
void _delLesserNodes()
{
Node current = head;
Node maxnode = head;
Node temp;
while (current != null && current.next != null ) {
if (current.next.data < maxnode.data) {
temp = current.next;
current.next = temp.next;
temp = null ;
}
else {
current = current.next;
maxnode = current;
}
}
}
void push( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
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;
}
void printList()
{
Node temp = head;
while (temp != null ) {
System.out.print(temp.data + " " );
temp = temp.next;
}
System.out.println();
}
public static void main(String args[])
{
LinkedList llist = new LinkedList();
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();
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
self .head = new_node
def printList( self ):
temp = self .head
while (temp is not None ):
print (temp.data, end = " " )
temp = temp. next
print ( "\n" )
def delLesserNodes( self ):
self .reverseList()
self ._delLesserNodes()
self .reverseList()
def _delLesserNodes( self ):
current = self .head
maxnode = self .head
while (current is not None and current. next is not None ):
if (current. next .data < maxnode.data):
temp = current. next
current. next = temp. next
else :
current = current. next
maxnode = current
def reverseList( self ):
current = self .head
prev = None
while (current is not None ):
next = current. next
current. next = prev
prev = current
current = next
self .head = prev
llist = LinkedList()
llist.push( 3 )
llist.push( 2 )
llist.push( 6 )
llist.push( 5 )
llist.push( 11 )
llist.push( 10 )
llist.push( 15 )
llist.push( 12 )
print ( "Given linked list" )
llist.printList()
llist.delLesserNodes()
print ( "Modified Linked List" )
llist.printList()
|
C#
using System;
class LinkedList
{
public Node head;
public class Node
{
public int data;
public Node next;
public Node( int d)
{
data = d;
next = null ;
}
}
void delLesserNodes()
{
reverseList();
_delLesserNodes();
reverseList();
}
void _delLesserNodes()
{
Node current = head;
Node maxnode = head;
Node temp;
while (current != null && current.next != null )
{
if (current.next.data < maxnode.data)
{
temp = current.next;
current.next = temp.next;
temp = null ;
}
else
{
current = current.next;
maxnode = current;
}
}
}
void push( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
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;
}
void printList()
{
Node temp = head;
while (temp != null )
{
Console.Write(temp.data + " " );
temp = temp.next;
}
Console.WriteLine();
}
public static void Main( string []args)
{
LinkedList llist = new LinkedList();
llist.push(3);
llist.push(2);
llist.push(6);
llist.push(5);
llist.push(11);
llist.push(10);
llist.push(15);
llist.push(12);
Console.WriteLine( "Given Linked List" );
llist.printList();
llist.delLesserNodes();
Console.WriteLine( "Modified Linked List" );
llist.printList();
}
}
|
Javascript
<script>
var head;
class Node {
constructor(val) {
this .data = val;
this .next = null ;
}
}
function delLesserNodes() {
reverseList();
_delLesserNodes();
reverseList();
}
function _delLesserNodes() {
var current = head;
var maxnode = head;
var temp;
while (current != null && current.next != null ) {
if (current.next.data < maxnode.data) {
temp = current.next;
current.next = temp.next;
temp = null ;
}
else {
current = current.next;
maxnode = current;
}
}
}
function push(new_data) {
var new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
function reverseList() {
var current = head;
var prev = null ;
var next;
while (current != null ) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
function printList() {
var temp = head;
while (temp != null ) {
document.write(temp.data + " " );
temp = temp.next;
}
document.write();
}
push(3);
push(2);
push(6);
push(5);
push(11);
push(10);
push(15);
push(12);
document.write( "Given Linked List<br/>" );
printList();
delLesserNodes();
document.write( "<br/>Modified Linked List<br/>" );
printList();
</script>
|
OutputGiven Linked List
12 15 10 11 5 6 2 3
Modified Linked List
15 11 6 3
Time complexity: O(n) where n is no of nodes in the Linked list
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.
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int data;
Node* next;
Node( int data) {
this ->data = data;
this ->next = nullptr;
}
};
class LLUtil {
public :
Node* createLL( int arr[], int n) {
Node* head = new Node(arr[0]);
Node* temp = head;
Node* newNode = nullptr;
for ( int i = 1; i < n; i++) {
newNode = new Node(arr[i]);
temp->next = newNode;
temp = temp->next;
}
return head;
}
void printLL(Node* head) {
while (head != nullptr) {
cout << head->data << " " ;
head = head->next;
}
cout << endl;
}
};
Node* deleteNodesOnRightSide(Node* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
Node* nextNode = deleteNodesOnRightSide(head->next);
if (nextNode->data > head->data) {
return nextNode;
}
head->next = nextNode;
return head;
}
int main() {
int arr[] = {12, 15, 10, 11, 5, 6, 2, 3};
int n = sizeof (arr) / sizeof (arr[0]);
LLUtil llu;
Node* head = llu.createLL(arr, n);
cout << "Given Linked List" << endl;
llu.printLL(head);
head = deleteNodesOnRightSide(head);
cout << "Modified Linked List" << endl;
llu.printLL(head);
return 0;
}
|
Java
import java.io.*;
class Node {
int data;
Node next;
public Node( int data){
this .data = data;
this .next = null ;
}
}
class LLUtil{
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;
}
public void printLL(Node head){
while (head != null ){
System.out.print(head.data + " " );
head = head.next;
}
System.out.println();
}
}
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);
}
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;
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LLUtil:
def createLL( self ,arr):
head = Node(arr[ 0 ])
temp = head
newNode = None
for i in range ( 1 , len (arr)):
newNode = Node(arr[i])
temp. next = newNode
temp = temp. next
return head
def printLL( self , head):
while head ! = None :
print (head.data, end = " " )
head = head. next
print ()
def deleteNodesOnRightSide(head):
if head = = None or head. next = = None :
return head
nextNode = deleteNodesOnRightSide(head. next )
if nextNode.data > head.data:
return nextNode
head. next = nextNode
return head
if __name__ = = '__main__' :
arr = [ 12 , 15 , 10 , 11 , 5 , 6 , 2 , 3 ]
llu = LLUtil()
head = llu.createLL(arr)
print ( "Given Linked List" )
llu.printLL(head)
head = deleteNodesOnRightSide(head)
print ( "Modified Linked List" )
llu.printLL(head)
|
C#
using System;
class Node {
public int data;
public Node next;
public Node( int data){
this .data = data;
this .next = null ;
}
}
class LLUtil{
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;
}
public void printLL(Node head){
while (head != null ){
Console.Write(head.data + " " );
head = head.next;
}
Console.WriteLine();
}
}
class GFG {
static void Main( string [] args) {
int [] arr = {12,15,10,11,5,6,2,3};
LLUtil llu = new LLUtil();
Node head = llu.createLL(arr);
Console.WriteLine( "Given Linked List" );
llu.printLL(head);
head = deleteNodesOnRightSide(head);
Console.WriteLine( "Modified Linked List" );
llu.printLL(head);
}
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;
}
}
|
Javascript
<script>
class Node {
constructor(val) {
this .data = val;
this .next = null ;
}
}
function createLL(arr) {
var head = new Node(arr[0]);
var temp = head;
var newNode = null ;
for (i = 1; i < arr.length; i++) {
newNode = new Node(arr[i]);
temp.next = newNode;
temp = temp.next;
}
return head;
}
function printLL(head) {
while (head != null ) {
document.write(head.data + " " );
head = head.next;
}
document.write( "<br/>" );
}
function deleteNodesOnRightSide(head) {
if (head == null || head.next == null )
return head;
var nextNode = deleteNodesOnRightSide(head.next);
if (nextNode.data > head.data)
return nextNode;
head.next = nextNode;
return head;
}
var arr = [ 12,15,10,11,5,6,2,3];
var head = createLL(arr);
document.write( "Given Linked List<br/>" );
printLL(head);
head = deleteNodesOnRightSide(head);
document.write( "<br/>Modified Linked List<br/>" );
printLL(head);
</script>
|
OutputGiven Linked List
12 15 10 11 5 6 2 3
Modified Linked List
15 11 6 3
Time complexity: O(n) where n is no of nodes in the Linked list
Auxiliary Space: O(n)
Source:
https://www.geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-linked-lists-6
Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem.