Coding-ninjas-data-st.-through-java
Coding-ninjas-data-st.-through-java copied to clipboard
Base case 1 and Base case 2 must be added .
public class Solution { public static LinkedListNode<Integer> swap_nodes(LinkedListNode<Integer> head,int i,int j) { if(head==null){ // base case 1 return head; } if(i==j){ // base case 2 return head; } LinkedListNode<Integer> 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; } prev=temp; temp=temp.next; pos++; } if(p1!=null) { p1.next=c2; } else{ head=c2; } if(p2!=null){ p2.next=c1; } else{ head=c1; } LinkedListNode<Integer> temp1=c2.next; c2.next=c1.next; c1.next=temp1; return head; } }