Use Java language. Write a program to add two polynomials. Use a linked list imp
ID: 3631200 • Letter: U
Question
Use Java language.Write a program to add two polynomials. Use a linked list
implementation. If the polynomials have M and N terms, respectively, please
clarify the time complexity of your program (you can specify this as the
comments of your program). Here are the sample input format:
+7x^9+2.3x^6+2x^2+4x^0
+15x^8-3.3x^2+-7x^0
The program should output:
+7x^9+15x^8+2.3x^6-1.3x^2+-3x^0
Explanation / Answer
#include class poly { private : struct polynode { float coeff ; int exp ; polynode *link ; } *p ; public : poly( ) ; void poly_append ( float c, int e ) ; void display_poly( ) ; void poly_add( poly &l1, poly &l2 ) ; ~poly( ) ; } ; poly :: poly( ) { p = NULL ; } void poly :: poly_append ( float c, int e ) { polynode *temp = p ; if ( temp == NULL ) { temp = new polynode ; p = temp ; } else { while ( temp -> link != NULL ) temp = temp -> link ; temp -> link = new polynode ; temp = temp -> link ; } temp -> coeff = c ; temp -> exp = e ; temp -> link = NULL ; } void poly :: display_poly( ) { polynode *temp = p ; int f = 0 ; cout 0 ) cout coeff = temp2 -> coeff ; z -> exp = temp2 -> exp ; temp2 = temp2 -> link ; } else { if ( temp1 -> exp > temp2 -> exp ) { z -> coeff = temp1 -> coeff ; z -> exp = temp1 -> exp ; temp1 = temp1 -> link ; } else { if ( temp1 -> exp == temp2 -> exp ) { z -> coeff = temp1 -> coeff + temp2 -> coeff ; z -> exp = temp1 -> exp ; temp1 = temp1 -> link ; temp2 = temp2 -> link ; } } } } while ( temp1 != NULL ) { if ( p == NULL ) { p = new polynode ; z = p ; } else { z -> link = new polynode ; z = z -> link ; } z -> coeff = temp1 -> coeff ; z -> exp = temp1 -> exp ; temp1 = temp1 -> link ; } while ( temp2 != NULL ) { if ( p == NULL ) { p = new polynode ; z = p ; } else { z -> link = new polynode ; z = z -> link ; } z -> coeff = temp2 -> coeff ; z -> exp = temp2 -> exp ; temp2 = temp2 -> link ; } z -> link = NULL ; } poly :: ~poly( ) { polynode *q ; while ( p != NULL ) { q = p -> link ; delete p ; p = q ; } } void main( ) { poly p1 ; p1.poly_append ( 1.4, 5 ) ; p1.poly_append ( 1.5, 4 ) ; p1.poly_append ( 1.7, 2 ) ; p1.poly_append ( 1.8, 1 ) ; p1.poly_append ( 1.9, 0 ) ; coutRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.