Академический Документы
Профессиональный Документы
Культура Документы
Mohammad Nazmul Haque Lecturer, Dept. of CSE More on lists. Circular lists. Doubly linked lists.
Polynomials
A( x ) =a m x e 1
m 1
+ m x e a 2
m 2
+ + 0xe ... a
Representation typedef struct poly_node *poly_pointer; typedef struct poly_node { int coef; int expon; poly_pointer next; }; poly_pointer a, b, c; coef expon link
Example
a = 3x + 2 x +1
14 8
14
null
b = 8 x 14 3x 10 +10 x 6
b 8 14 -3 10 10 6 null
Adding Polynomials
3 14 a 8 14 b 11 14 d 3 14 8 14 11 14 2 8 -3 10 1 0 10 6
} for (; a; a = a->next) attach(a->coef, a->expon, &rear); for (; b; b=b->next) attach(b->coef, b->expon, &rear); rear->next = NULL; temp = front; front = front->next; free(temp); return front;
case -1: /* a->expon < b->expon */ attach(b->coef, b->expon, &rear); b= b->next; break; case 0: /* a->expon == b->expon */ sum = a->coef + b->coef; if (sum) attach(sum,a->expon,&rear); a = a->next; b = b->next; break; case 1: /* a->expon > b->expon */ attach(a->coef, a->expon, &rear); a = a->next;
Analysis
(1) (2) coefficient additions 0 additions min(m, n) where m (n) denotes the number of terms in A (B). exponent comparisons extreme case em-1 > fm-1 > em-2 > fm-2 > > e0 > f0 m+n-1 comparisons creation of new nodes extreme case m + n new nodes summary O(m+n)
(3)
Attach a Term
void attach(float coefficient, int exponent, poly_pointer *ptr) {
/* create a new node attaching to the node pointed to by ptr. ptr is updated to point to this new node. */
poly_pointer temp; temp = (poly_pointer) malloc(sizeof(poly_node)); if (IS_FULL(temp)) { fprintf(stderr, The memory is full\n); exit(1); } temp->coef = coefficient; temp->expon = exponent; (*ptr)->next = temp; *ptr = temp;
3 14
2 8
avail
1 0
...
X1
X2
X3
Insertion
void insertFront (pnode* ptr, pnode node) { /* insert a node in the list with head (*ptr)->next */ if (IS_EMPTY(*ptr)) { *ptr= node; node->next = node; /* circular link */ } else { node->next = (*ptr)->next; (1) (*ptr)->next = node; (2) } } X3 X2 X1
(2)
ptr
(1)
List length
int length(pnode ptr) { pnode temp; int count = 0; if (ptr) { temp = ptr; do { count++; temp = temp->next; } while (temp!=ptr); } return count; }
Update pointers for every operation performed on the list How to remove an element from the tail of the list ?
entry node
down
row value
col
right
aij
i aij
Linked Representation
4 4 0 2 11 1 0 12 1 1 5 2 1 -4 3 3 -15 Circular linked list