From f8b8c0a9ff048bf0b03d4a7ff715cf5171cd0016 Mon Sep 17 00:00:00 2001 From: Arsh Ali <56296638+arshali2774@users.noreply.github.com> Date: Tue, 9 Jan 2024 04:39:11 +0530 Subject: [PATCH] Update Linked List 2:Swap two Node of LL Old code was giving runtime error in test case 3 --- Linked List 2:Swap two Node of LL | 82 +++++++++++++++++-------------- 1 file changed, 46 insertions(+), 36 deletions(-) diff --git a/Linked List 2:Swap two Node of LL b/Linked List 2:Swap two Node of LL index 4929f34..3fda001 100644 --- a/Linked List 2:Swap two Node of LL +++ b/Linked List 2:Swap two Node of LL @@ -1,44 +1,54 @@ -public class Solution -{ - public static LinkedListNode swap_nodes(LinkedListNode head,int i,int j) - { - LinkedListNode temp=head,prev=null,c1=null,c2=null,p1=null,p2=null; - int pos=0; - while(temp!=null) - { - if(pos==i) - { - p1=prev; - c1=temp; +// class Node { +// T data; +// Node next; + +// public Node(T data) { +// this.data = data; +// } +// } + +public class Solution { + + public static Node swapNodes(Node head, int i, int j) { + // Check if i and j are the same + if (i == j) { + return head; + } + + Node temp = head, prev = null, c1 = null, c2 = null, p1 = null, p2 = null; + int pos = 0; + + while (temp != null) { + if (pos == i) { + p1 = prev; + c1 = temp; + } else if (pos == j) { + p2 = prev; + c2 = temp; } -else if(pos==j) -{ - p2=prev; - c2=temp; -} - prev=temp; - temp=temp.next; + prev = temp; + temp = temp.next; pos++; } - if(p1!=null) - { - p1.next=c2; - } - else{ - head=c2; - } - if(p2!=null){ - p2.next=c1; + + if (p1 != null) { + p1.next = c2; + } else { + head = c2; } - else{ - head=c1; + + if (p2 != null) { + p2.next = c1; + } else { + head = c1; } - LinkedListNode temp1=c2.next; - c2.next=c1.next; - c1.next=temp1; - return head; - } -} + Node temp1 = c2.next; + c2.next = c1.next; + c1.next = temp1; + return head; + } + // Utility method to print the linked list +}