61
Chapter 4 Lists Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Dynamically Linked Stacks and Queues Queues Polynomials Polynomials Chain Chain Circularly Linked Lists Circularly Linked Lists Equivalence Relations Equivalence Relations Doubly Linked Lists Doubly Linked Lists

Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Embed Size (px)

Citation preview

Page 1: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Chapter 4 ListsChapter 4 Lists

PointersPointers Singly Linked ListsSingly Linked Lists Dynamically Linked Stacks and QueuesDynamically Linked Stacks and Queues PolynomialsPolynomials ChainChain Circularly Linked ListsCircularly Linked Lists Equivalence RelationsEquivalence Relations Doubly Linked ListsDoubly Linked Lists

Page 2: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Pointers (1/5)Pointers (1/5) Consider the following Consider the following alphabetized alphabetized list of three letter list of three letter

English words ending in English words ending in atat::((batbat, , catcat, , satsat, , vatvat))

If we store this list in an arrayIf we store this list in an array AddAdd the word the word matmat to this listto this list

move move satsat and and vatvat one position to the right before we insert one position to the right before we insert matmat..

RemoveRemove the word the word catcat from the listfrom the list move move satsat and and vatvat one position to the left one position to the left

Problems of a sequence representation (ordered list)Problems of a sequence representation (ordered list) Arbitrary insertion and deletion from arrays can be very Arbitrary insertion and deletion from arrays can be very

time-consumingtime-consuming Waste storageWaste storage

Page 3: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Pointers (2/5)Pointers (2/5) An elegant solution: using linked representationAn elegant solution: using linked representation

Items may be placed anywhere in memory.Items may be placed anywhere in memory. In a sequential representation the In a sequential representation the order of elementsorder of elements is is

the same as in the the same as in the ordered listordered list, while in a linked , while in a linked representation these two sequences representation these two sequences need not be the need not be the samesame..

Store the Store the addressaddress, or , or locationlocation, of the next element in , of the next element in that list for accessing elements in the correct order that list for accessing elements in the correct order with each element.with each element.

Thus, associated with each list element is a Thus, associated with each list element is a nodenode which contains both a which contains both a data componentdata component and a and a pointer pointer to the next item in the list. The pointers are often to the next item in the list. The pointers are often called called linkslinks..

Page 4: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Pointers (3/5)Pointers (3/5) C provides extensive supports for pointers.C provides extensive supports for pointers.

Two most important operators used with the pointer type :Two most important operators used with the pointer type :

&& the address operator the address operator

** the dereferencing (or indirection) operator the dereferencing (or indirection) operator Example:Example:

If we have the declaration:If we have the declaration: int i, *pi;int i, *pi;

then then ii is an integer variable and is an integer variable and pipi is a pointer to an integer. is a pointer to an integer.

If we say:If we say: pi = &i;pi = &i;

then &then &ii returns the address of returns the address of ii and assigns it as the value of and assigns it as the value of pipi..

To assign a value to To assign a value to ii we can say: we can say: i = 10; i = 10; or or *pi = 10;*pi = 10;

Page 5: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Pointers (4/5)Pointers (4/5) Pointers can be dangerousPointers can be dangerous

Using pointers: high degree of flexibility and efficiency, but daUsing pointers: high degree of flexibility and efficiency, but dangerous as well.ngerous as well. It is a wise practice to set all pointers to It is a wise practice to set all pointers to NULLNULL when they are not actu when they are not actu

ally pointing to an object.ally pointing to an object. Another: using explicit Another: using explicit type casttype cast when converting between pointer typ when converting between pointer typ

es.es. Example:Example:pi = malloc(sizeof(int));/*assign to pi a pointer to int*/pi = malloc(sizeof(int));/*assign to pi a pointer to int*/

pf = (float *)pi; /*casts int pointer to float pointer*/pf = (float *)pi; /*casts int pointer to float pointer*/

In many systems, pointers have the same size as type In many systems, pointers have the same size as type intint.. Since Since intint is the default type specifier, some programmers omit the return t is the default type specifier, some programmers omit the return t

ype when defining a function.ype when defining a function. The return type defaults to The return type defaults to intint which can later be interpreted as a pointer. which can later be interpreted as a pointer.

Page 6: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Pointers (5/5)Pointers (5/5) Using dynamically allocated storageUsing dynamically allocated storage

When programming, you may not know how much space yWhen programming, you may not know how much space you will need, nor do you wish to allocate some vary large aou will need, nor do you wish to allocate some vary large area that may never be required.rea that may never be required. C provides C provides heapheap, for allocating storage at run-time., for allocating storage at run-time. You may call a function, You may call a function, mallocmalloc, and request the amount of memor, and request the amount of memor

y you need.y you need. When you no longer need an area of memory, you may free it by cWhen you no longer need an area of memory, you may free it by c

alling another function, alling another function, freefree, and return the area of memory to the , and return the area of memory to the system.system.

Example:Example: request memory

return memory

Page 7: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (1/15)Singly Linked Lists (1/15)

Linked lists are drawn as an order sequence of nodLinked lists are drawn as an order sequence of nodes with links represented as arrows (Figure 4.1).es with links represented as arrows (Figure 4.1). The name of the pointer to the first node in the list is the nThe name of the pointer to the first node in the list is the n

ame of the list. (the list of Figure 4.1 is called ame of the list. (the list of Figure 4.1 is called ptrptr.).) Notice that we do not explicitly put in the values of pointers, but siNotice that we do not explicitly put in the values of pointers, but si

mply draw allows to indicate that they are there.mply draw allows to indicate that they are there.

Page 8: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (2/15)Singly Linked Lists (2/15)

The nodes do not resident in sequential locationsThe nodes do not resident in sequential locations The locations of the nodes may change on The locations of the nodes may change on

different runsdifferent runs

Data Field

Link Field

Node

. . . Null

ptr

chain

Page 9: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (3/15)Singly Linked Lists (3/15) Why it is easier to make arbitrary insertions and Why it is easier to make arbitrary insertions and

deletions using a linked list?deletions using a linked list? To insert the word To insert the word matmat between between catcat can can satsat, we must:, we must:

Get a node that is currently unused; let its address be Get a node that is currently unused; let its address be paddrpaddr.. Set the data field of this node to Set the data field of this node to matmat.. Set Set paddrpaddr’s link field to point to the address found in the link f’s link field to point to the address found in the link f

ield of the node containing ield of the node containing catcat.. Set the link field of the node containing Set the link field of the node containing catcat to point to to point to paddrpaddr..

Page 10: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (4/15)Singly Linked Lists (4/15)

Delete mat from the list:Delete mat from the list: We only need to find the element that immediately We only need to find the element that immediately

precedes mat, which is cat, and set its link field to point precedes mat, which is cat, and set its link field to point to mat’s link (Figure 4.3).to mat’s link (Figure 4.3).

We have not moved any data, and although the link field We have not moved any data, and although the link field of mat still points to sat, mat is no longer in the list.of mat still points to sat, mat is no longer in the list.

Page 11: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (5/15)Singly Linked Lists (5/15)

We need the following capabilities to make linked We need the following capabilities to make linked representations possible:representations possible: Defining a node’s structure, that is, the fields it containDefining a node’s structure, that is, the fields it contain

s. We use s. We use self-referential structuresself-referential structures, discussed in Sect, discussed in Section 2.2 to do this.ion 2.2 to do this.

Create new nodes when we need them. (Create new nodes when we need them. (mallocmalloc)) Remove nodes that we no longer need. (Remove nodes that we no longer need. (freefree))

Page 12: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (6/15)Singly Linked Lists (6/15) 2.2.4 Self-Referential Structures2.2.4 Self-Referential Structures

One or more of its components is a pointer to itself.One or more of its components is a pointer to itself.

typedef struct list {typedef struct list {char data;char data;list *link;list *link;}}

list item1, item2, item3;list item1, item2, item3;item1.data=‘a’;item1.data=‘a’;item2.data=‘b’;item2.data=‘b’;item3.data=‘c’;item3.data=‘c’;item1.link=item2.link=item3.link=NULL;item1.link=item2.link=item3.link=NULL;

a b c

Construct a list with three nodesitem1.link=&item2;item2.link=&item3;malloc: obtain a node (memory)free: release memory

Page 13: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (7/15)Singly Linked Lists (7/15) Example 4.1 [List of words ending in at]:

Declarationtypedef struct list_node *list_pointer;struct list_node {

char data [4];list_pointer link;

}; Creation

list_pointer ptr =NULL; Testing

#define IS_EMPTY(ptr) (!(ptr)) Allocation

ptr=(list_pointer) malloc (sizeof(list_node)); Return the spaces:

free(ptr);

Page 14: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (8/15)Singly Linked Lists (8/15)

b a t \0 NULL

address offirst node

ptr data ptr link

ptr

Figure 4.4:Referencing the fields of a node(p.142)

e -> name (*e).namestrcpy(ptr -> data, “bat”);ptr -> link = NULL;

Page 15: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (9/15)Singly Linked Lists (9/15) Example 4.2 [Two-node linked list]:

typedef struct list_node *list_pointer;typedef struct list_node *list_pointer;typedef struct list_node {typedef struct list_node {

int data;int data;list_pointer link;list_pointer link;

};};list_pointer ptr =NULL;list_pointer ptr =NULL;

Program 4.2: Create a two-node listlist_pointer create2( )list_pointer create2( ){{

/* create a linked list with two nodes *//* create a linked list with two nodes */list_pointer first, second;list_pointer first, second;first = (list_pointer) malloc(sizeof(list_node));first = (list_pointer) malloc(sizeof(list_node));second = (list_pointer) malloc(sizeof(list_node));second = (list_pointer) malloc(sizeof(list_node));second -> link = NULL;second -> link = NULL;second -> data = 20;second -> data = 20;first -> data = 10;first -> data = 10;first ->link = second;first ->link = second;return first;return first;

}}10 20

ptr

#define IS_FULL(ptr) (!(ptr))

When returns NULL if there is no more memory.

NULL

Page 16: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

node

2010

50

NULL

temp

ptr

Singly Linked Lists (10/15)Singly Linked Lists (10/15)• InsertionInsertion

Observation insert a new node with data = 50 into the list ptr aft

er node

Page 17: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (11/15)Singly Linked Lists (11/15) Implement Insertion:

void insert(list_pointer *ptr, List_pointer node)void insert(list_pointer *ptr, List_pointer node)

{{

/* insert a new node with data = 50 into the list ptr after nod/* insert a new node with data = 50 into the list ptr after node */e */

list_pointer temp;list_pointer temp;

temp=(list_pointer)malloc(sizeof(list_node));temp=(list_pointer)malloc(sizeof(list_node));

if(IS_FULL(temp)){if(IS_FULL(temp)){

fprintf(stderr, “The memory is full\n”);fprintf(stderr, “The memory is full\n”);

exit(1);exit(1);

}}

temp->data=50;temp->data=50;temp 50

Page 18: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (12/15)Singly Linked Lists (12/15)if(*ptr){if(*ptr){ //nonempty list//nonempty list

temp->link = node->link;temp->link = node->link;node->link = temp;node->link = temp;

}}else{else{ //empty list//empty list

temp->link = NULL;temp->link = NULL;*ptr = temp;*ptr = temp;

}}}}

node

2010

50

NULL

temp

ptr

Page 19: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (13/15)Singly Linked Lists (13/15) DeletionDeletion

Observation: delete node from the listObservation: delete node from the list

ptr trial node

ptr trial node

NULL10 50 20

NULL10 20

ptr

NULL10 50 20

Page 20: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (14/15)Singly Linked Lists (14/15) Implement Deletion:Implement Deletion:

void delete(list_pointer *ptr, list_pointer trail, list_pointer void delete(list_pointer *ptr, list_pointer trail, list_pointer node)node)

{{

/* delete node from the list, trail is the preceding node pt/* delete node from the list, trail is the preceding node ptr is the head of the list */r is the head of the list */

if(trail)if(trail)

trail->link = node->link;

elseelse

*ptr = (*ptr)->link;

free(node);free(node);

}}

ptr trial node

10 50 NULL20

Page 21: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Singly Linked Lists (15/15)Singly Linked Lists (15/15)

Print out a list (traverse a list) Program 4.5:Program 4.5: Printing a list Printing a list

void print_list(list_pointer ptr)void print_list(list_pointer ptr)

{{

printf(“The list contains: “);printf(“The list contains: “);

for ( ; for ( ; ptrptr; ptr = ptr->link); ptr = ptr->link)

printf(“%4d”, ptr->data);printf(“%4d”, ptr->data);

printf(“\n”);printf(“\n”);

}}

Page 22: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Dynamically Linked Dynamically Linked Stacks and Queues (1/8)Stacks and Queues (1/8)

When several stacks and queues coexisted, there When several stacks and queues coexisted, there was no efficient way to represent them was no efficient way to represent them sequentially.sequentially. Notice that direction of links for both stack and the queue Notice that direction of links for both stack and the queue

facilitate easy insertion and deletion of nodes.facilitate easy insertion and deletion of nodes. Easily add or delete a node form the top of the stack.Easily add or delete a node form the top of the stack. Easily add a node to the rear of the queue and add or delete a Easily add a node to the rear of the queue and add or delete a

node at the front of a queue.node at the front of a queue.

Page 23: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Dynamically Linked Dynamically Linked Stacks and Queues (2/8)Stacks and Queues (2/8)

Represent n stacks

top item link

link

NULL

...

Stack

Page 24: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Dynamically Linked Dynamically Linked Stacks and Queues (3/8)Stacks and Queues (3/8)

Push in the linked stackvoid add(stack_pointer *top, element item){void add(stack_pointer *top, element item){

/* add an element to the top of the stack */ /* add an element to the top of the stack */ Pushstack_pointer temp = (stack_pointer) malloc (sizeof (stack));stack_pointer temp = (stack_pointer) malloc (sizeof (stack));if (IS_FULL(temp)) {if (IS_FULL(temp)) {

fprintf(stderr, “ The memory is full\n”);fprintf(stderr, “ The memory is full\n”);exit(1);exit(1);

}}temp->item = item; temp->link = *top;*top= temp;

}}

top link

NULL

...

item linktemp

link

Page 25: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Dynamically Linked Dynamically Linked Stacks and Queues (4/8)Stacks and Queues (4/8)

Pop from the linked stackelement delete(stack_pointer *top) {element delete(stack_pointer *top) {/* delete an element from the stack */ /* delete an element from the stack */ PopPop

stack_pointer temp = *top;stack_pointer temp = *top;element item;element item;if (IS_EMPTY(temp)) {if (IS_EMPTY(temp)) {

fprintf(stderr, “The stack is empty\n”);fprintf(stderr, “The stack is empty\n”);exit(1);exit(1);

}}item = temp->item;*top = temp->link;free(temp);return item;return item;

}}

item link

link

NULL

...

link

toptemp

Page 26: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Dynamically Linked Dynamically Linked Stacks and Queues (5/8)Stacks and Queues (5/8)

Represent n queues

front item link

link

NULL

...

Queue

rear

Add to

Delete from

Page 27: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Dynamically Linked Dynamically Linked Stacks and Queues (6/8)Stacks and Queues (6/8)

enqueue in the linked queuein the linked queue

front link

NULL

...

itemtemp

link

rear

NULL

Page 28: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Dynamically Linked Dynamically Linked Stacks and Queues (7/8)Stacks and Queues (7/8)

dequeue from the linked queue (similar to push)from the linked queue (similar to push)

link

NULL

... link

front item linktemp

rear

Page 29: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Dynamically Linked Dynamically Linked Stacks and Queues (8/8)Stacks and Queues (8/8)

The solution presented above to the n-stack, m-The solution presented above to the n-stack, m-queue problem is both computationally and queue problem is both computationally and conceptually simple.conceptually simple. We no longer need to shift stacks or queues to make We no longer need to shift stacks or queues to make

space.space. Computation can proceed as long as there is memory Computation can proceed as long as there is memory

available.available.

Page 30: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Polynomials (1/9)Polynomials (1/9)

Representing Polynomials As Singly Linked ListsRepresenting Polynomials As Singly Linked Lists The manipulation of symbolic polynomials, has a classic example The manipulation of symbolic polynomials, has a classic example

of list processing.of list processing. In general, we want to represent the polynomial:In general, we want to represent the polynomial:

Where the Where the aai i are nonzero coefficients and the are nonzero coefficients and the eeii are nonnegat are nonnegative integer exponents such that ive integer exponents such that

eem-1 m-1 > > eem-2m-2 > > … … >> ee1 1 > > ee0 0 0 .≧ 0 .≧ We will represent each term as a node containing We will represent each term as a node containing coefficientcoefficient and and

exponentexponent fields, as well as a fields, as well as a pointer pointer to the next termto the next term..

0101)( ee

m xaxaxA m

Page 31: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Polynomials (2/9)Polynomials (2/9)

Assuming that the coefficients are integers, the type declAssuming that the coefficients are integers, the type declarations are:arations are:typedef struct poly_node *poly_pointer;typedef struct poly_node *poly_pointer;typedef struct poly_node {typedef struct poly_node {

int coef;int coef; int expon;int expon;poly_pointer link;poly_pointer link;

};};poly_pointer a,b,d;poly_pointer a,b,d;

Draw Draw poly_nodespoly_nodes as: as:

coefcoef exponexpon linklink

123 814 xxa

b x x x 8 3 1014 10 6

Page 32: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Polynomials (3/9)Polynomials (3/9) Adding Polynomials

To add two polynomials,we examine their terms starting at the nodes pointed to by a and b. If the exponents of the two terms are equal

1. add the two coefficients

2. create a new term for the result.

If the exponent of the current term in a is less than b1. create a duplicate term of b

2. attach this term to the result, called d

3. advance the pointer to the next term in b.

We take a similar action on a if a->expon > b->expon.

Figure 4.12 generating the first three term of d = a+b (next page)

Page 33: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

PolynomialsPolynomials(4/9)(4/9)

Page 34: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

PolynomialsPolynomials(5/9)(5/9)

Add two Add two polynomialspolynomials

Page 35: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Polynomials (6/9)Polynomials (6/9) Attach a node to the end of a listAttach a node to the end of a list

void attach(float coefficient, int exponent, poly_pointer *ptr){/* create a new node with coef = coefficient and expon = exponent,

attach it 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));/* create new node */if (IS_FULL(temp)) {

fprintf(stderr, “The memory is full\n”);exit(1);

}temp->coef = coefficient; /* copy item to the new node */temp->expon = exponent;(*ptr)->link = temp; /* attach */*ptr = temp; /* move ptr to the end of the list */

}

Page 36: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Polynomials (7/9)Polynomials (7/9) Analysis of paddAnalysis of padd

1. coefficient additions0 additions min(m, n)where m (n) denotes the number of terms in A (B).

2. exponent comparisonsextreme case:em-1 > fm-1 > em-2 > fm-2 > … > e1 > f1 > e0 > f0 m+n-1 comparisons

3. creation of new nodesextreme case: maximum number of terms in d is m+n m + n new nodessummary: O(m+n)

))(())(( 01010101

ffn

eem xbxbxBxaxaxA nm

Page 37: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Polynomials (8/9)Polynomials (8/9) A Suite for PolynomialsA Suite for Polynomials

e(x) = a(x) * b(x) + d(x)

poly_pointer a, b, d, e;

...

a = read_poly();

b = read_poly();

d = read_poly();

temp = pmult(a, b);

e = padd(temp, d);

print_poly(e);temp is used to hold a partial result.By returning the nodes of temp, we may use it to hold other polynomials

read_poly()

print_poly()

padd()

psub()

pmult()

Page 38: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Polynomials (9/9)Polynomials (9/9) Erase PolynomialsErase Polynomials

erase frees the nodes in erase frees the nodes in temptemp

void erase (poly_pointer *ptr){void erase (poly_pointer *ptr){

/* erase the polynomial pointed to by ptr *//* erase the polynomial pointed to by ptr */

poly_pointer temp;poly_pointer temp;

while ( *ptr){while ( *ptr){

temp = *ptr;temp = *ptr;

*ptr = (*ptr) -> link;*ptr = (*ptr) -> link;

free(temp);free(temp);

}}

}}

Page 39: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Chain (1/3)Chain (1/3) Chain:Chain:

A singly linked list in which the last node has a null linkA singly linked list in which the last node has a null link Operations for chainsOperations for chains

Inverting a chainInverting a chain For a list of For a list of lengthlength 1 nodes, the ≧ 1 nodes, the ≧ whilewhile loop is executed loop is executed lengtlengt

hh times and so the computing time is linear or O( times and so the computing time is linear or O( lengthlength).).

...

...

NULL

×NULL

lead

lead

invert

Page 40: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Chain Chain (2/3)(2/3)

...NULL NULL

trialmiddlelead

Two extra pointers

Page 41: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Chain (3/3)Chain (3/3) Concatenates two chainsConcatenates two chains Concatenates two chains, ptr1 and ptr2.Concatenates two chains, ptr1 and ptr2. Assign the list Assign the list

ptr1 followed ptr1 followed by the list ptr2.by the list ptr2.

O(length of list ptr1)

NULL

ptr1

NULL

ptr2

temp

Page 42: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Circularly Linked Lists (1/10)Circularly Linked Lists (1/10)

Circular Linked listCircular Linked list The link field of the last node points to the first The link field of the last node points to the first

node in the list.node in the list. ExampleExample

Represent a polynomial Represent a polynomial ptrptr = 3x = 3x1414+2x+2x88+1 as a +1 as a circularly linked list.circularly linked list.

ptr 33 1414 22 88 11 00

Page 43: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Circularly Linked Lists (2/10)Circularly Linked Lists (2/10) Maintain an Available ListMaintain an Available List

We free nodes that are no longer in use so that we mWe free nodes that are no longer in use so that we may reuse these nodes lateray reuse these nodes later

We can obtain an efficient erase algorithm for circular We can obtain an efficient erase algorithm for circular lists, by maintaining our own list (as a chain) of nodes lists, by maintaining our own list (as a chain) of nodes that have been “freed”.that have been “freed”.

Instead of usingInstead of using malloc malloc andand free free, we now use get_no, we now use get_node (program 4.13) and ret_node (program 4.14).de (program 4.13) and ret_node (program 4.14).

avail ... NULL

List of freed nodes

Page 44: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Circularly Linked Lists (3/10)Circularly Linked Lists (3/10) Maintain an Available List (cont’d)Maintain an Available List (cont’d)

When we need a new node, we examine this list. When we need a new node, we examine this list. If the list is not empty, then we may use one of its nodes.If the list is not empty, then we may use one of its nodes.

Only when the Only when the

list is empty we list is empty we do need to use do need to use mallocmalloc to to create a new create a new node.node.

Page 45: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Circularly Linked Lists (4/10)Circularly Linked Lists (4/10) Maintain an Available List (cont’d)Maintain an Available List (cont’d) Insert ptr to the front of this list

Let Let availavail be a variable of type poly_pointer that points be a variable of type poly_pointer that points to the first node in our list of freed nodes.to the first node in our list of freed nodes.

Henceforth, we call this list the available space list or Henceforth, we call this list the available space list or availavail list. list.

Initially, we set Initially, we set availavail to to NULLNULL

Page 46: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Circularly Linked Lists (5/10)Circularly Linked Lists (5/10)

Maintain an Available ListMaintain an Available List Erase a circular list in a fixed Erase a circular list in a fixed

amount (amount (constantconstant) ) of time of time O(1) independent of the numbindependent of the number of nodeser of nodes in the list using in the list using cceraseerase

temp

ptr

NULLavail

紅色 link 所連接而成的 chain

Page 47: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Circularly Linked Lists (6/10)Circularly Linked Lists (6/10) We must handle the We must handle the zero polynomialzero polynomial as a special c as a special c

ase. To avoid it, we introduce a ase. To avoid it, we introduce a head nodehead node into eac into each polynomialh polynomial each polynomial, zero or nonzero, contains one additional each polynomial, zero or nonzero, contains one additional

node.node. The The expoexpon and n and coefcoef fields of this node are irrelevant. fields of this node are irrelevant.

Why ?

So !

Page 48: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Circularly Linked Circularly Linked Lists (7/10)Lists (7/10)

For fit the For fit the circular list with hcircular list with head node represead node representationentation We may remove We may remove

the test for (*ptr) fthe test for (*ptr) from rom cerasecerase

Changes the origiChanges the original nal paddpadd to to cpadcpaddd

/* head node */

/*a->expon=-1, so b->expont > -1 */

/* link to the first node */

Page 49: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Circularly Linked Lists (8/10)Circularly Linked Lists (8/10) Operations for circularly linked listsOperations for circularly linked lists

Question: What happens when we want to insert a new node

at the front of the circular linked list ptr?

Answer: move down the entire length of ptr.

Possible Solution:

ptr x1 x2 x3

x1 x2 x3 ptr

Page 50: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Circularly Linked Lists (9/10)Circularly Linked Lists (9/10)

x1 x2 x3 ptr

node

Insert a new nodInsert a new node at the front of e at the front of a circular lista circular list

To insert To insert nodenode a at the rear, we onlt the rear, we only need to add thy need to add the additional state additional statement ement *ptr = nod*ptr = nodee to the else cla to the else clause of use of insert_froinsert_frontnt

Page 51: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Circularly Linked Lists (10/10)Circularly Linked Lists (10/10)

Finding the length of a circular listFinding the length of a circular list

Page 52: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Equivalence Relations (1/6)Equivalence Relations (1/6) Reflexive RelationReflexive Relation

for any polygon x, x ≡ x (e.g., x is electrically equivalent to itself)for any polygon x, x ≡ x (e.g., x is electrically equivalent to itself)

Symmetric RelationSymmetric Relation for any two polygons x and y, if x ≡ y, then y ≡ x.for any two polygons x and y, if x ≡ y, then y ≡ x.

Transitive RelationTransitive Relation for any three polygons x, y, and z, if x ≡ y and y ≡ z, then x ≡ z.for any three polygons x, y, and z, if x ≡ y and y ≡ z, then x ≡ z.

Definition:Definition: A relation over a set, A relation over a set, SS, is said to be an , is said to be an equivalence relation ove ove

rr S iff S iff it is it is symmertric symmertric,, reflexive reflexive, and, and transitive transitive over S.over S.

Example:Example: ““equal to” relationship is an equivalence relationequal to” relationship is an equivalence relation

Page 53: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Equivalence Relations (2/6)Equivalence Relations (2/6) Example:Example: if we have 12 polygons numbered 0 through 11if we have 12 polygons numbered 0 through 11

0 0 4 4, , 3 3 1 1, , 6 6 10 10, , 8 8 9 9, , 7 7 4 4, , 6 6 8 8, , 3 3 5 5, , 2 2 11 11, , 11 11 0 0

we can partition the twelve polygons into the following we can partition the twelve polygons into the following equivalence classes:equivalence classes:

{0, 2, 4, 7, 11};{1, 3, 5};{6, 8, 9,10}{0, 2, 4, 7, 11};{1, 3, 5};{6, 8, 9,10} Two phases to determine equivalenceTwo phases to determine equivalence

First phase: the equivalence pairs (i, j) are read in and First phase: the equivalence pairs (i, j) are read in and stored.stored.

Second phase:Second phase: we begin at 0 and find all pairs of the form (0, j). we begin at 0 and find all pairs of the form (0, j).

Continue until the entire equivalence class containing 0 has been Continue until the entire equivalence class containing 0 has been found, marked, and printed.found, marked, and printed.

Next find another object not yet output, and repeat Next find another object not yet output, and repeat the above process.the above process.

Page 54: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Equivalence Relation (3/6)Equivalence Relation (3/6) Program to find equivalence classesProgram to find equivalence classes

void main(void){void main(void){short int out[MAX_SIZE];short int out[MAX_SIZE];node_pointer seq[MAX_SIZE];node_pointer seq[MAX_SIZE];node_pointer x, y, top;node_pointer x, y, top;int i, j, n;int i, j, n;printf(“Enter the size (<=%d) ”, MAX_SIZE);printf(“Enter the size (<=%d) ”, MAX_SIZE);scanf(“%d”, &n);scanf(“%d”, &n);for(i=0; i<n; i++){for(i=0; i<n; i++){

/*initialize seq and out *//*initialize seq and out */out[i] = TRUE;out[i] = TRUE; seq[i] = NULL;seq[i] = NULL;

}}/* Phase 1 *//* Phase 1 *//* Phase 2 *//* Phase 2 */

}}

typedef struct node *node_pointer;typedef struct node *node_pointer;typedef struct node {typedef struct node {

int data;int data;node_pointer link;node_pointer link;

};};

#include <stdio.h>#include <stdio.h>#define MAX_SIZE#define MAX_SIZE 2424#define IS_FULL(ptr)#define IS_FULL(ptr) (!(ptr))(!(ptr))#define FALSE#define FALSE 00#define TRUE#define TRUE 11

Page 55: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Equivalence Relations (4/6)Equivalence Relations (4/6) Phase 1: Phase 1: read in and store the equivalence pairs <i, j>

Insert x to the top of lists seq[i]

Insert x to the top of lists seq[j]

(1) (2)

[11]

[10]

[9]

[8]

[7]

[6]

[5]

[4]

[3]

[2]

[1]

[0]

0 4, 3 1, 6 10, 8 9, 7 4, 6 8, 3 5, 2 11, 11 0

4 NULL

0 NULL

1 NULL

3 NULL

10 NULL

6 NULL

9 NULL

8 NULL

4 NULL

7

8

6

5

3 NULL

11 NULL

2 NULL0

11

Page 56: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Equivalence Relations (5/6)Equivalence Relations (5/6)

Phase 2: begin at 0 and find all pairs of the form <0, j>, where 0 begin at 0 and find all pairs of the form <0, j>, where 0

and j are in the same equivalence classand j are in the same equivalence class by transitivity, all pairs of the form <j, k> imply that k by transitivity, all pairs of the form <j, k> imply that k

in the same equivalence class as 0in the same equivalence class as 0 continue this way until we have found, marked, and continue this way until we have found, marked, and

printed the entire equivalent class containing 0printed the entire equivalent class containing 0

Page 57: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Equivalence Relations (6/6)Equivalence Relations (6/6)

Phase 2Phase 2

[11]

[10]

[9]

[8]

[7]

[6]

[5]

[4]

[3]

[2]

[1]

[0] 4 NULL

0 NULL

1 NULL

3 NULL

10 NULL

6 NULL

9 NULL

8 NULL

4 NULL

7

8

6

5

3 NULL

11 NULL

2 NULL0

11

New class: 0

i=[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

out:

x

top j= 11y

11

4

4

7

7

0402

2

1101

Page 58: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Doubly Linked Lists (1/4)Doubly Linked Lists (1/4) Singly linked lists pose problems because we caSingly linked lists pose problems because we ca

n move easily only in the direction of the linksn move easily only in the direction of the links

Doubly linked list has at least three fieldsDoubly linked list has at least three fields left link field(left link field(llinkllink), data field(), data field(itemitem), right link field(), right link field(rlinkrlink).). The necessary declarations:The necessary declarations:

typedef struct node *node_pointer;typedef struct node *node_pointer;

typedef struct node{typedef struct node{

node_pointer llink;node_pointer llink;

element item;element item;

node_pointer rlink;node_pointer rlink;

};};

... NULL

ptr?

Page 59: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Doubly Linked Lists (2/4)Doubly Linked Lists (2/4) SampleSample

doubly linked circular with head node: (Figure 4.23)doubly linked circular with head node: (Figure 4.23)

empty double linked circular list with head node (Fiempty double linked circular list with head node (Figure 4.24)gure 4.24)

suppose that suppose that ptr ptr points to any node in a doubly linkpoints to any node in a doubly linked list, then:ed list, then: ptr = ptr -> llink -> rlink = ptr -> rlink -> llinkptr = ptr -> llink -> rlink = ptr -> rlink -> llink

Page 60: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Doubly Linked Lists (3/4)Doubly Linked Lists (3/4) Insert nodeInsert node

Head node

llink item rlink

New node

node

Page 61: Chapter 4 Lists Pointers Pointers Singly Linked Lists Singly Linked Lists Dynamically Linked Stacks and Queues Dynamically Linked Stacks and Queues Polynomials

Doubly Linked Lists (4/4)Doubly Linked Lists (4/4) Delete nodeDelete node

Head node

llink item rlink

deleted node