Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Base case 1 and Base case 2 must be added . #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Harshadaware11
Copy link

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;
}
}

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;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant