Add two polynomials using Linked List | Java solution

Approach:- we know that in polynomial addition only those polynomials can be added together who have same power.
we are given two LL that consists of two polynomials we have to add. first compare the power of polynomials from each list with each other:-
1.) if the powers are same then we add the coeff of the polynomials and then add their result into the resultant list. and move the next pointer of the first and second list one step forward
2.) if the powers are diff. then the polynomial with greater power is considered since in our resultant list polynomial with the greater power comes first as per rules of equation.
3.)the list whose power is greater is shifted to next node while the list with smaller power remains there because we might find a power equal to smaller power in the list of greater power in the future (i hope this is not confusing).
4.)all of the above steps happen in a while loop which runs until one of the either list is exhausted.
5.)after that we just add the list which isnt exhausted at the end of the resultant list.
6.)dont worry if both gets exhausted at the same time since the if condition will take care of that too.

class Node{
    int coeff;
    int pow;
    Node next;
    Node(int a,int b)
    {
        coeff=a;
        pow=b;
        next=null;
    }
	class prac
{
    public static Node addPolynomial(Node p1,Node p2)
    {
Node res=new Node(-1,-1);
Node temp=res;
while(p1!=null&&p2!=null){
    if(p1.pow==p2.pow){
        temp.next=new Node(p1.coeff+p2.coeff,p2.pow);
        p1=p1.next;
        p2=p2.next;
    }
   else if(p1.pow>p2.pow){
temp.next=p1;
p1=p1.next;
    }
    else{
     temp.next=p2;
p2=p2.next;   
    } 
temp=temp.next;
    }
    if(p1==null)
    temp.next=p2;
    else
    temp.next=p1;
    return res.next;
}
}
Comments (2)