Here I'm using Iterative for delete a Node
Time Complexity of this approach will be : O(N);
Another Approach is Recursively
import java.sql.SQLOutput;
import java.util.Scanner;
public class removeElement {
public static void print(Node<Integer> head){
System.out.print("New Node:");
while(head != null){
System.out.print( head.data + " ");
head = head.next;
}
}
public static Node<Integer> removeElement(Node<Integer> head, int pos) {
if (head == null) {
return head;
}
if (pos == 0) { //agar position hi zero hai jisko remove krna hai to aage badha do
head = head.next;
}
Node<Integer> tempNode = head;
int count = 0;
while (count < pos - 1 && tempNode != null) {
tempNode = tempNode.next;
count++;
}
// pos
// 1 2 3 4 5
// Temp
// count
//first iteration me pos ke 1 kam tak chlna hai , kya count pos se 1 chota hai
// yes count filhal 0 me hai to ek bar aage kar do aur temp ko bhi 1 aage bdha do
/* pos
//1 2 3 4 5
// count
temp
>> abhi dubara check karega kya count chota hai pos-1 se bilkul condition
true ho rhi to ek bar aur aage bdhega
pos
//1 2 3 4 5
// count
temp
is iteration me count and temp pos tak phuch jayenge lekin jaise hi wha phucha loop break ho
jayega aur count and temp 2 element me hi aa jayenge aur loop se bahar ho jayega
*/
if (tempNode != null && tempNode.next != null) {
tempNode.next = tempNode.next.next;
}
return head;
/* pos
// //1 2 3 4 5
// // count
temp
ab yaha condition check karega kya tempNode aur tempNode ka next null hai ?
nhi hai to temp ke next me temp ke next ka next connect kar do
// //1 2 4 5
// // count
temp
kuch is trh temp ho jayega aur pos hamara delete ho jayega
*/
}
public static Node<Integer> takeInput() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Node:");
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();
removeElement(head,4);
print(head);
}
}
Comments
Post a Comment