diff --git a/Data Structures in JAVA/Linked List 1/Delete_Node_in_LL.java b/Data Structures in JAVA/Linked List 1/Delete_Node_in_LL.java index 219916e..cfc82dc 100644 --- a/Data Structures in JAVA/Linked List 1/Delete_Node_in_LL.java +++ b/Data Structures in JAVA/Linked List 1/Delete_Node_in_LL.java @@ -67,26 +67,30 @@ public LinkedListNode(T data) { *****************************************************************/ public class Solution { - public static LinkedListNode deleteNode(LinkedListNode head, int i) { - // Write your code here. + public static Node deleteNode(Node head, int pos) { + if (head == null) { + return null; // If the list is empty, nothing to delete + } - if(head==null ) - return head; - if(i==0) - return head.next; - int count=0; - LinkedListNode temp=head; - while(temp!=null && count temp = head; + while (temp != null && i < pos - 1) { + temp = temp.next; + i++; } - if(temp==null) + + // If temp is null or temp.next is null, it means the position is out of bounds + if (temp == null || temp.next == null) { return head; - if(temp.next!=null) - temp.next=temp.next.next; - + } + + // Update the link to skip the node at position 'pos' + temp.next = temp.next.next; return head; - } + } }