Base case 1 and Base case 2 must be added . #9
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
public class Solution
{
public static LinkedListNode swap_nodes(LinkedListNode head,int i,int j)
{
if(head==null){ // base case 1
return head;
}
if(i==j){ // base case 2
return head;
}
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;
}
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 temp1=c2.next;
c2.next=c1.next;
c1.next=temp1;
return head;
}
}