Docsity

Data Structures and Algorithm Analysis: Linked Lists and Polynomials, Slides of Data Structures and Algorithms

Partial preview of the text

Download Data Structures and Algorithm Analysis: Linked Lists and Polynomials and more Slides Data Structures and Algorithms in PDF only on Docsity!

Data Structures &

Algorithm Analysis

Applications of Linked Lists

• Stacks and Queues Implemented with Linked

Lists

• Polynomials Implemented with Linked Lists

– Remember the array based implementation?

  • Hint: two strategies, one efficient in terms of space,

one in terms of running time

typedef struct poly_node *poly_pointer;

typedef struct poly_node {

int coef;

int expon;

poly_pointer next;

poly_pointer a, b, c;

A x a m x a x a x

e m

m e^ m e

− − 1 2 0

1 2 0

coef expon link

Representation

Polynomials

a

b

a = 3 x + 2 x + 1

14 8

b = 8 x − 3 x + 10 x

14 10 6

null

null

Example

a

8 14 -3 10^10

b

a->expon > b->expon

d

Adding Polynomials (cont’d)

poly_pointer padd(poly_pointer a, poly_pointer b)

{

poly_pointer front, rear, temp; int sum; rear =(poly_pointer)malloc(sizeof(poly_node)); if (IS_FULL(rear)) { fprintf(stderr, “The memory is full\n”); exit(1); } front = rear; while (a && b) { switch (COMPARE(a->expon, b->expon)) {

Adding Polynomials (cont’d)

(1) coefficient additions

0 ≤ additions ≤ min(m, n)

where m (n) denotes the number of terms in A (B).

(2) exponent comparisons

extreme case

e m-1 > f m-1 > e m-2 > f m-2 > … > e 0 > f

m+n-1 comparisons

(3) creation of new nodes

extreme case

m + n new nodes

summary O(m+n)

Analysis

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;

}

Attach a Term

ptr

ptr

avail

avail

temp

circular list vs. chain

Circularly linked lists

X 1  X 2  X 3 

a

What happens when we insert a node to the front of a circular

linked list?

Problem: move down the whole list.

Operations in a circular list

X 1  X 2  X 3 ^

a

Keep a pointer points to the last node.

A possible solution:

int length(pnode ptr) { pnode temp; int count = 0; if (ptr) { temp = ptr; do { count++; temp = temp->next; } while (temp!=ptr); } return count;

}

List length

Doubly Linked List

• Keep a pointer to the next and the previous

element in the list

typedef struct node *pnode; typedef struct node { char data [4]; pnode next; pnode prev; }

Doubly Linked List – removeLast()

• Running

time?

• How does

this

compare to

simply

Doubly Linked List

• insertFirst

• swapElements