From 31a4ce1c7d43e36e9ec3a18f1c318370feeb411c Mon Sep 17 00:00:00 2001 From: Prince Kumar <147418512+prince62058@users.noreply.github.com> Date: Wed, 17 Apr 2024 01:34:32 +0530 Subject: [PATCH] Update Delete_Node_in_LL.java Signed-off-by: Prince Kumar <147418512+prince62058@users.noreply.github.com> --- .../Linked List 1/Delete_Node_in_LL.java | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) 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; - } + } }