100 likes | 163 Views
Data Structures CSCI 132, Fall 2018 Lecture 13 Queues as Linked Lists, Polynomial Arithmetic. Queues as Linked Lists. front. entry 1. entry 2. entry 3. class Queue { public: Queue(); bool empty() const; Error_code append (const Queue_entry &item); Error_code serve( );
E N D
Data StructuresCSCI 132, Fall 2018Lecture 13Queues as Linked Lists, Polynomial Arithmetic
Queues as Linked Lists front entry 1 entry 2 entry 3 class Queue { public: Queue(); bool empty() const; Error_code append (const Queue_entry &item); Error_code serve( ); Error_code retrieve(Queue_entry &item) const; ~Queue(); Queue(const Queue &original); void operator =(const Queue &original); protected: Node *front, *rear; }; rear
append( ) implementation Error_code Queue :: append(const Queue_entry &item) { }
append( ) implementation Error_code Queue :: append(const Queue_entry &item) { Node *new_rear = new Node(item); }
Implementing serve( ) Error_code Queue :: serve( ) { }
coeff exponent p 3 2 4 1 -1 0 Polynomial Arithmetic p = 3x2 + 4x -1 q = x3 - 2x2 - 4x + 7 r = p + q = x3 + x2 + 6 Rules: Order elements from highest exponent to lowest. Terms with coefficient of zero are not included. No two terms have the same exponent.
The Term struct struct Term { int degree; double coefficient; Term (int exponent = 0, double scalar = 0); }; Term :: Term(int exponent, double scalar) /* Post: The Term is initialized with the given coefficient and exponent, or with default parameter values of 0. */ { degree = exponent; coefficient = scalar; }
The Polynomial class typedef Term Queue_entry; class Polynomial: private Extended_queue { // Use private inheritance. public: void read( ); void print( ) const; void equals_sum(Polynomial p, Polynomial q); void equals_difference(Polynomial p, Polynomial q); void equals_product(Polynomial p, Polynomial q); Error_code equals_quotient(Polynomial p, Polynomial q); int degree( ) const; private: void mult_term(Polynomial p, Term t); };
Polynomial addition void Polynomial :: equals_sum(Polynomial p, Polynomial q) { clear( ); while (!p.empty( ) || !q.empty( )) { Term p_term, q_term; if (p.degree( ) > q.degree( )) { p.serve_and_retrieve(p_term); append(p_term); } else if (q.degree( ) > p.degree( )) { q.serve_and_retrieve(q_term); append(q_term); } else { p.serve_and_retrieve(p_term); q.serve_and_retrieve(q_term); if (p_term.coefficient + q_term.coefficient != 0) { Term answer_term(p_term.degree, p_term.coefficient + q_term.coefficient); append(answer_term); } } } }
The degree( ) function int Polynomial :: degree( ) const { if (empty( )) { return -1; } Term lead; retrieve(lead); return lead.degree; }