Skip to main content

Delete Node Recursively

Another Approach is Iterative>>


Time Complexity O(N);

 

import java.util.*;
public class removeNode_recursively {



public static void print(Node<Integer> head){
System.out.println("New Node:");
while(head != null){
System.out.print(head.data + " ");
head = head.next;
}
}



public static Node<Integer> removeRecursively(Node<Integer> head, int pos){
if(head == null){
return head;
}

if(pos == 0){
head = head.next;
}

Node<Integer> smallInput = removeRecursively(head.next,pos -1);
head.next = smallInput;
return head;

}

public static Node<Integer> takeInput(){
Scanner scan = new Scanner(System.in);

Node<Integer> head = null;
Node<Integer> tail = null;

int data = 0;
while(data != -1){
data = scan.nextInt();
Node<Integer> newData = new Node<Integer>(data);

if(head == null){
head = newData;
tail = newData;
}

else{
tail.next = newData;
tail = newData;

}
}return head;


}


public static void main(String[] args) {

Node<Integer> head =takeInput();
removeRecursively(head,4);
print(head);




}
}

Comments