cs235102 data structures chapter 4 lists. pointers singly linked lists dynamically linked stacks...

22
CS235102 CS235102 Data Structures Data Structures Chapter 4 Lists Chapter 4 Lists

Post on 22-Dec-2015

237 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

CS235102 CS235102 Data StructuresData Structures

Chapter 4 ListsChapter 4 Lists

Page 2: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 3: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

Pointers (1/5)Pointers (1/5) Consider the following Consider the following alphabetizedalphabetized 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 4: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 pointerpointer 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 5: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 6: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 7: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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

Free memory

Page 8: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 9: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 10: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 11: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 12: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 13: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 14: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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;typedef 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 15: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 16: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 17: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 18: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 19: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 20: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 21: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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 22: CS235102 Data Structures Chapter 4 Lists.  Pointers  Singly Linked Lists  Dynamically Linked Stacks and Queues  Polynomials  Chain  Circularly Linked

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”);

}}