2015-03-11 4 views
0

я следующий код ..Добавление двух многочленов хранятся в виде связанных списков

import java.io.*; 
    class Link 

    { 

     public int coeff; 

     public int exp; 

     Link next; 

     public Link(int a,int b) 
    { 
     coeff=a;exp=b; 
    } 

     public int retcof(){ 
     return coeff; 
    } 

     public int retexp() { 
     return exp; 
    } 

     public void displayLink(){ 
     System.out.print(coeff+"x^"+exp); 
    } 


    } 


    class LinkList{ 


    Link first,last; 


    public LinkList(){ 
       ; 
    } 

     public void insertfirst(int x,int y) 
    { 
     Link newLink=new Link(x,y); 

     newLink.next=first; 

     first=newLink; 
    } 

     public void displayList() 
    { 

     Link x=first; 


     while(x!=null) 
    { 


     x.displayLink(); 

     x=x.next; 

      if(x!=null) 

      System.out.print("+"); 

    } 



    } 


     /*public void add(LinkList a,LinkList b) 

     { 
     int p; 

     Link current1=a.first; 

     Link current2=b.first; 

     LinkList qwe=new LinkList(); 

     while(current2!=null) 

     { 

     while(current1!=null) 

     { 
     if(current1.retexp()>current2.retexp()) 

     qwe.insertfirst(current1.retcof(),current1.retexp()); 
     else if(current2.retexp()>current1.retexp()) 

     qwe.insertfirst(current2.retcof(),current2.retexp()); 
     else if(current1.retexp()==current2.retexp()) 

     { 

     p=current1.retcof()+current2.retcof(); 


    qwe.insertfirst(p,current2.retexp()); 

     } 

     current1=current1.next; 



     } 

     current2=current2.next; 


     } 

     qwe.displayList(); 

     }*/ 


public void add(LinkList a,LinkList b) 
{ 
Link current1=a.first; 

    Link current2=b.first; 

    LinkList qwe=new LinkList(); 
while (current1 != null || current2 != null) {  
    //now check if one of them has ended  
    if (current1 == null&&current2!=null) //first ended; insert remaining nodes from second; return result  
    {qwe.insertfirst(current2.retcof(),current2.retexp());current2 = current2.next;} 
    if (current2 == null&&current1!=null) //second ended, insert remaining nodes from first; return result 
    {qwe.insertfirst(current1.retcof(),current1.retexp()); current1 = current1.next;} 
    //otherwise, compare exponents  
    if ((current1 != null && current2 != null)&&(current1.retexp() > current2.retexp())) 
     {qwe.insertfirst(current1.retcof(),current1.retexp()); current1 = current1.next;}  
     //advance the first pointer, but not he second   
    else if ((current1 != null && current2 != null)&&(current1.retexp() < current2.retexp())) 
     {qwe.insertfirst(current2.retcof(),current2.retexp()); current2 = current2.next;} 
     //in this case advancing the second pointer, but not the first  
    else if((current1 != null && current2 != null)&&(current1.retexp() == current2.retexp()))//exponents are equal  
     {qwe.insertfirst(current2.retcof()+current1.retcof(),current2.retexp());; current1 = current1.next; current2 = current2.next;}  
     //add the members and advance both pointers  
} 
qwe.displayList(); 
} 





    } 

     class zz 
    { 


     public static void main(String [] args)throws IOException 
    { 

     int degree1,degree2,num1,itr; 


     LinkList wow=new LinkList(); 


     LinkList wow1=new LinkList(); 

    //wow.insertfirst(1,2); 


     System.out.println("Enter the degree of the first polynomial "+" "); 


     DataInputStream X=new DataInputStream(System.in); 


     String s=X.readLine(); 

     degree1=Integer.parseInt(s); 


     itr=degree1; 


     while(itr>=0){ 

     System.out.print("enter the coeff of x^"+itr+" : "); 

     s=X.readLine(); 
     num1=Integer.parseInt(s); 

     wow.insertfirst(num1,itr); 

     itr--; 

     } 


     wow.displayList(); 


     System.out.println("\n"+"Enter the degree of the second polynomial "+" "); 


     s=X.readLine(); 

     degree2=Integer.parseInt(s); 

     itr=degree2; 


     while(itr>=0) 
    { 

     System.out.print("enter the coeff of x^"+itr+" : "); 

     s=X.readLine(); 
     num1=Integer.parseInt(s); 

     wow1.insertfirst(num1,itr); 
    itr--; 

    } 


     wow1.displayList(); 


     System.out.println("\n"); 


     wow.add(wow,wow1); 

    } 

    } 

EDIT: ОСНОВНОЙ. Возникла проблема с функцией add(), которая была исправлена ​​прямо сейчас!

Есть ли другой эффективный способ сделать это? Как сделать этот код проще, особенно функцию add(), которая кажется немного сложной.

+0

Какая линия line 140? –

+0

@ Ryan J Я понятия не имею. Это то, что компилятор продолжает говорить. Вышеприведенный код - все, что у меня есть – user4275686

+0

Какая IDE вы используете? –

ответ

1

Самое большое, что я вижу здесь ваше отсутствие обработки должным образом случай, когда любой из ваших current переменные null, таким образом, что предотвратит NPE (как вы уже видели) ...

Ваш код, лучше отформатирован ниже имеет несколько вопросов, касающихся обработки null

while (current1 != null || current2 != null) {  
    //now check if one of them has ended  
    if (current1 == null) //first ended; insert remaining nodes from second; return result  
    { 
     qwe.insertfirst(current2.retcof(),current2.retexp()); 
     current2 = current2.next; 
    } 
    if (current2 == null) //second ended, insert remaining nodes from first; return result 
    { 
     qwe.insertfirst(current1.retcof(),current1.retexp()); 
     current1 = current1.next; 
    } 
    //otherwise, compare exponents  
    if (current1.retexp() > current2.retexp()) 
    { 
     qwe.insertfirst(current1.retcof(),current1.retexp()); 
     current1 = current1.next; 
    }  
    //advance the first pointer, but not he second   
    else if (current1.retexp() < current2.retexp()) 
    { 
     qwe.insertfirst(current2.retcof(),current2.retexp()); 
     current2 = current2.next; 
    } 
    //in this case advancing the second pointer, but not the first  
    else //exponents are equal      
    {   
     qwe.insertfirst(current2.retcof()+current1.retcof(),current2.retexp()); 
     current1 = current1.next; 
     current2 = current2.next; 
    }  
    //add the members and advance both pointers  
} 

Рассмотрим случай, когда current2 является null

Ваш код правильно определит, что он равен нулю, и введите свой второй блок if, и продвиньте current1.

Однако, вы не защищают от доступа полей на current2 в последующих if блоков, так что вы будете в конечном итоге получить NPE на:

//otherwise, compare exponents  
if (current1.retexp() > current2.retexp()) // right here! you access current2, but it's null :(

Вы должны обойти все это если любая из ваших ссылок null, так что вы не попадаете в этот беспорядок.

+0

ОК, поэтому, прежде всего, я подключил каждую, если/else, иначе - если лестница. Во-вторых, для последних двух else-if (после первого исправления в остальном останется else) я включил '(current1! = Null && current2! = Null) && (current1.retexp()> current2.retexp())' в оба из них. Вот и все.Он решил проблему. Благодарю вас, сэр. – user4275686

+0

Такая же проблема сохраняется. – user4275686

+0

Я вернул свои исправления if-else. Мои новые исправления: третий, если block 'if ((current1! = Null && current2! = Null) && (current1.retexp()> current2.retexp()))' follow else-if 'else if ((current1! = null && current2! = null) && (current1.retexp() user4275686

0

Полный разрешенный код.

import java.io.*; 
class Link 

{ 

    public int coeff; 

    public int exp; 

    Link next; 

    public Link(int a,int b) 
{ 
    coeff=a;exp=b; 
} 

    public int retcof(){ 
    return coeff; 
} 

    public int retexp() { 
    return exp; 
} 

    public void displayLink(){ 
    System.out.print(coeff+"x^"+exp); 
} 


} 


class LinkList{ 


Link first,last; 


public LinkList(){ 
      ; 
} 

    public void insertfirst(int x,int y) 
{ 
    Link newLink=new Link(x,y); 

    newLink.next=first; 

    first=newLink; 
} 

    public void displayList() 
{ 

    Link x=first; 


    while(x!=null) 
{ 


    x.displayLink(); 

    x=x.next; 

     if(x!=null) 

     System.out.print("+"); 

} 



} 



public void add(LinkList a,LinkList b) 
{ 

Link current1=a.first; 


    Link current2=b.first; 


    LinkList qwe=new LinkList(); 

    while (current1 != null || current2 != null) {  

    if (current1 == null&&current2!=null) 

    {qwe.insertfirst(current2.retcof(),current2.retexp());current2 = current2.next;} 
    if (current2 == null&&current1!=null) 

    {qwe.insertfirst(current1.retcof(),current1.retexp()); current1 = current1.next;} 

    if ((current1 != null && current2 != null)&&(current1.retexp() > current2.retexp())) 

     {qwe.insertfirst(current1.retcof(),current1.retexp()); current1 = current1.next;}  

    else if ((current1 != null && current2 != null)&&(current1.retexp() < current2.retexp())) 

     {qwe.insertfirst(current2.retcof(),current2.retexp()); current2 = current2.next;} 

    else if((current1 != null && current2 != null)&&(current1.retexp() == current2.retexp()))//exponents are equal  

     {qwe.insertfirst(current2.retcof()+current1.retcof(),current2.retexp());; current1 = current1.next; current2 = current2.next;}  
} 
qwe.displayList(); 
} 





} 

    class k 
{ 


    public static void main(String [] args)throws IOException 
{ 

    int degree1,degree2,num1,itr; 


    LinkList wow=new LinkList(); 


    LinkList wow1=new LinkList(); 


    System.out.println("Enter the degree of the first polynomial "+" "); 


    DataInputStream X=new DataInputStream(System.in); 


    String s=X.readLine(); 

    degree1=Integer.parseInt(s); 


    itr=degree1; 


    while(itr>=0){ 

    System.out.print("enter the coeff of x^"+itr+" : "); 

    s=X.readLine(); 
    num1=Integer.parseInt(s); 

    wow.insertfirst(num1,itr); 

    itr--; 

    } 


    wow.displayList(); 


    System.out.println("\n"+"Enter the degree of the second polynomial "+" "); 


    s=X.readLine(); 

    degree2=Integer.parseInt(s); 

    itr=degree2; 


    while(itr>=0) 
{ 

    System.out.print("enter the coeff of x^"+itr+" : "); 

    s=X.readLine(); 
    num1=Integer.parseInt(s); 

    wow1.insertfirst(num1,itr); 
itr--; 

} 


    wow1.displayList(); 


    System.out.println("\n"); 


    wow.add(wow,wow1); 

} 

} 

 Смежные вопросы

  • Нет связанных вопросов^_^