Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

49
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter Chapter 13 13 Pointers and Linked Pointers and Linked Lists Lists
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    214
  • download

    0

Transcript of Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Page 1: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 13Chapter 13Pointers and Linked ListsPointers and Linked Lists

Page 2: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 2

OverviewOverview

13.1 Nodes and Linked Lists13.1 Nodes and Linked Lists

(up(up to, but not including the last section on page to, but not including the last section on page

749.)749.)

13.2 Stacks and Queues13.2 Stacks and Queues

Page 3: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

13.113.1Nodes and Linked ListsNodes and Linked Lists

Page 4: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 4

1010 1212 1414 endendhead

Nodes and Linked ListsNodes and Linked Lists A linked list is a list that can grow and shrink A linked list is a list that can grow and shrink

while the program is running.while the program is running. A linked list is constructed using pointersA linked list is constructed using pointers A linked list often consists of structs or A linked list often consists of structs or

classes that contain a pointer variable classes that contain a pointer variable connecting them to other dynamic variablesconnecting them to other dynamic variables

A linked list can be visualized as items, drawn A linked list can be visualized as items, drawn as boxes, connected to other items by arrowsas boxes, connected to other items by arrows

Page 5: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

The boxes in the previous drawing represent The boxes in the previous drawing represent the nodes of a linked listthe nodes of a linked list Nodes contain the data item(s) and a Nodes contain the data item(s) and a

pointer that can point to another node of pointer that can point to another node of the same typethe same type

The pointers point to the entire node, not The pointers point to the entire node, not an individual item that might be in the an individual item that might be in the nodenode

The arrows in the drawing represent pointers The arrows in the drawing represent pointers

Slide 13- 5

NodesNodes

Page 6: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Page 7: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 7

Nodes are implemented in C++ as structs or Nodes are implemented in C++ as structs or classesclasses Example: A structure to store two data items Example: A structure to store two data items

and a pointer to another node of the same and a pointer to another node of the same type, along with a type definition might be:type, along with a type definition might be: struct ListNode struct ListNode { string item; { string item; int count; int count; ListNode *link; ListNode *link; }; }; typedef ListNode* ListNodePtr; typedef ListNode* ListNodePtr;

This circular definition is allowed in C++

Implementing NodesImplementing Nodes

Page 8: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 8

The Head of a ListThe Head of a List

The box labeled head in the previous The box labeled head in the previous diagram is not a node, but a pointer diagram is not a node, but a pointer variable that points to a nodevariable that points to a node

Pointer variable head is declared as:Pointer variable head is declared as:

ListNodePtr head; ListNodePtr head;

Page 9: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 9

Accessing Items in a NodeAccessing Items in a Node

Using the previous diagr, this is one way to Using the previous diagr, this is one way to change the number in the first node from change the number in the first node from 10 to 12:10 to 12: (*head).count = 12; (*head).count = 12; head is a pointer variable so *head is the node head is a pointer variable so *head is the node

to which head points to which head points The parentheses are necessary because the The parentheses are necessary because the

dot operator . has higher precedence than the dot operator . has higher precedence than the dereference operator *dereference operator *

Page 10: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

The arrow operator -> combines the actions of The arrow operator -> combines the actions of the dereferencing operator * and the dot the dereferencing operator * and the dot operator to specify a member of a struct or object operator to specify a member of a struct or object pointed to by a pointer pointed to by a pointer

(*head).count = 12;(*head).count = 12;

can be written as can be written as

head->count = 12;head->count = 12;

The arrow operator is more commonly usedThe arrow operator is more commonly used

Slide 13- 10

The Arrow OperatorThe Arrow Operator

Page 11: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Page 12: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 12

NULLNULLThe defined constant NULL is used as…The defined constant NULL is used as… An end marker for a linked listAn end marker for a linked list

A program can step through a list of nodes by A program can step through a list of nodes by following the pointers, but when it finds a node following the pointers, but when it finds a node containing NULL, it knows it has come to the containing NULL, it knows it has come to the end of the listend of the list

The value of a pointer that has nothing to point toThe value of a pointer that has nothing to point to

The value of NULL is 0The value of NULL is 0

Any pointer can be assigned the value NULL:Any pointer can be assigned the value NULL: double* there = NULL; double* there = NULL;

Page 13: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 13

To Use NULLTo Use NULL

A definition of NULL is found in several A definition of NULL is found in several libraries, including <iostream> and libraries, including <iostream> and <cstddef><cstddef>

A using directive is not needed for NULLA using directive is not needed for NULL

Page 14: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 14

Linked ListsLinked ListsThe previous diagram depicts a linked listThe previous diagram depicts a linked list

A A linked listlinked list is a list of nodes in which each node is a list of nodes in which each node has a member variable that is a pointer that has a member variable that is a pointer that points to the next node in the listpoints to the next node in the list The first node is called the The first node is called the headhead The pointer variable head, points to the first nodeThe pointer variable head, points to the first node

The The pointer named headpointer named head is not the head of the is not the head of the list…it points to the head of the listlist…it points to the head of the list

The The last nodelast node contains a pointer set to contains a pointer set to NULLNULL

Page 15: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 15

Building a Linked List:Building a Linked List:The node DefinitionThe node Definition

Let's begin with a simple node definition:Let's begin with a simple node definition: struct Node struct Node { { int data; int data; Node *link; Node *link; }; }; typedef Node* NodePtr; typedef Node* NodePtr;

Page 16: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 16

Building a Linked List:Building a Linked List:Declaring Pointer Variable headDeclaring Pointer Variable head

With the node defined and a type definition With the node defined and a type definition to make our code easier to understand, we to make our code easier to understand, we can declare the pointer variable head:can declare the pointer variable head:

NodePtr head;NodePtr head; head is a pointer variable that will point head is a pointer variable that will point

to the head node when the node is to the head node when the node is created created

Page 17: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 17

Building a Linked List:Building a Linked List:Creating the First NodeCreating the First Node

To create the first node, the operator new To create the first node, the operator new is used to create a new dynamic variable:is used to create a new dynamic variable:

head = new Node;head = new Node;

Now head points to the first, and only, Now head points to the first, and only, node in the listnode in the list

Page 18: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 18

Building a Linked List:Building a Linked List:Initializing the NodeInitializing the Node

Now that head points to a node, we need Now that head points to a node, we need to give values to the member variables of to give values to the member variables of the node:the node:

head->data = 3;head->data = 3; head->link = NULL; head->link = NULL; Since this node is the last node, the link Since this node is the last node, the link

is set to NULLis set to NULL

Page 19: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 19

Function head_insertFunction head_insertIt would be better to create a function to insertIt would be better to create a function to insertnodes at the head of a list, such as:nodes at the head of a list, such as:

void head_insert(NodePtr& head, int void head_insert(NodePtr& head, int

the_number);the_number);

The first parameter is a NodePtr parameter that The first parameter is a NodePtr parameter that points to the first node in the linked listpoints to the first node in the linked list

The second parameter is the number to store in The second parameter is the number to store in the listthe list

Page 20: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Function head_insertFunction head_insert

head_insert will create a new node for head_insert will create a new node for the numberthe number

The number will be copied to the new The number will be copied to the new nodenode

The new node will be inserted in the The new node will be inserted in the list as the new head nodelist as the new head node

Page 21: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Create a new dynamic variable pointed to Create a new dynamic variable pointed to by temp_ptrby temp_ptr

Place the data in the new node called Place the data in the new node called *temp_ptr*temp_ptr

Make temp_ptr's link variable point to the Make temp_ptr's link variable point to the head node head node

Make the head pointer point to temp_ptrMake the head pointer point to temp_ptr

Slide 13- 21

Pseudocode for head_insertPseudocode for head_insert

Page 22: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Page 23: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

The pseudocode for head_insert can be writtenThe pseudocode for head_insert can be writtenin C++ using these lines in place of the lines of in C++ using these lines in place of the lines of pseudocode:pseudocode: NodePtr temp_ptr; //create temporary pointer NodePtr temp_ptr; //create temporary pointer

temp_ptr = new Node; // create the new nodetemp_ptr = new Node; // create the new node temp_ptr->data = the_number; //copy thetemp_ptr->data = the_number; //copy the

//number//number temp_ptr->link = head; //new node points to temp_ptr->link = head; //new node points to

//first node //first nodehead = temp_ptr; // head points to new head = temp_ptr; // head points to new // first node // first node

Slide 13- 23

Translating head_insert to C++Translating head_insert to C++

Page 24: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Page 25: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 25

An Empty ListAn Empty List

A list with nothing in it is called an empty listA list with nothing in it is called an empty list

An empty linked list has no head nodeAn empty linked list has no head node

The head pointer of an empty list is NULLThe head pointer of an empty list is NULL

head = NULL; head = NULL; Any functions written to manipulate a linked Any functions written to manipulate a linked

list should check to see if it works on the list should check to see if it works on the empty listempty list

Page 26: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

You might be tempted to write head_insert You might be tempted to write head_insert using the head pointer to construct the new using the head pointer to construct the new node:node:

head = new Node; head = new Node; head->data = the_number; head->data = the_number;

Now to attach the new node to the listNow to attach the new node to the list The node that head used to point to is The node that head used to point to is

now lost!now lost!

Slide 13- 26

Losing NodesLosing Nodes

Page 27: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Page 28: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 28

Memory LeaksMemory LeaksNodes that are lost by assigning their pointers a Nodes that are lost by assigning their pointers a new address are not accessible any longernew address are not accessible any longer

The program has no way to refer to the nodesThe program has no way to refer to the nodesand cannot delete them to return their memoryand cannot delete them to return their memoryto the freestoreto the freestore

Programs that lose nodes have a Programs that lose nodes have a memory leakmemory leak Significant memory leaks can cause system Significant memory leaks can cause system

crashescrashes Various operating systems are accused of Various operating systems are accused of

having memory leaks - particularly Windowshaving memory leaks - particularly Windows

Page 29: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 29

Searching a Linked ListSearching a Linked ListTo design a function that will locate a particularTo design a function that will locate a particularnode in a linked list:node in a linked list: We want the function to return a pointer to the We want the function to return a pointer to the

node so we can use the data if we find it, else node so we can use the data if we find it, else return NULLreturn NULL

The linked list is one argument to the functionThe linked list is one argument to the function The data we wish to find is the other argumentThe data we wish to find is the other argument This declaration will work:This declaration will work:

NodePtr search(NodePtr head, int target); NodePtr search(NodePtr head, int target);

Page 30: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Refining our functionRefining our function We will use a local pointer variable, named We will use a local pointer variable, named

herehere, to move through the list checking for , to move through the list checking for the targetthe target

The only way to move around a linked list The only way to move around a linked list is to follow pointersis to follow pointers

We will start with here pointing to the first We will start with here pointing to the first node and move the pointer from node to node and move the pointer from node to node following the pointer out of each nodenode following the pointer out of each node

Slide 13- 30

Function searchFunction search

Page 31: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Page 32: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 32

Pseudocode for searchPseudocode for searchMake pointer variable here point to the head Make pointer variable here point to the head nodenode

while (here does not point to a node containing while (here does not point to a node containing target AND here does not point to the last node) target AND here does not point to the last node) { { make here point to the next node make here point to the next node } }

If (here points to a node containing the target)If (here points to a node containing the target) return here; return here; else else return NULL; return NULL;

Page 33: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 33

Moving Through the ListMoving Through the ListThe pseudocode for search requires that The pseudocode for search requires that pointer here step through the listpointer here step through the list How does here follow the pointers from node How does here follow the pointers from node

to node?to node?

When here points to a node, here->link is the When here points to a node, here->link is the address of the next nodeaddress of the next node

To make here point to the next node, make To make here point to the next node, make the assignment:the assignment: here = here->link; here = here->link;

Page 34: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 34

Check for last node

A Refinement of searchA Refinement of searchThe search function can be refined in this way:The search function can be refined in this way:here = head;here = head;while (here->data != target && while (here->data != target &&

here->link != NULL)here->link != NULL) { { here = here->next; here = here->next; } } if (here->data = = target) if (here->data = = target) return here; return here; else else return NULL; return NULL;

Page 35: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Our search algorithm has a problemOur search algorithm has a problem If the list is empty, If the list is empty, herehere equals NULL equals NULL

before the while loop so…before the while loop so…

here->data is undefinedhere->data is undefined

here->link is undefinedhere->link is undefined The empty list requires a special case in The empty list requires a special case in

our search functionour search function A refined search function that handles an A refined search function that handles an

empty list is shown in the next slide.empty list is shown in the next slide.

Slide 13- 35

Searching an Empty ListSearching an Empty List

Page 36: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Page 37: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 37

Pointers as IteratorsPointers as IteratorsAn An iteratoriterator is a construct that allows you to is a construct that allows you to cycle through the data items in a data structurecycle through the data items in a data structureto perform an action on each itemto perform an action on each item An iterator can be an object of an iterator class, An iterator can be an object of an iterator class,

an array index, or simply a pointeran array index, or simply a pointer

A general outline using a pointer as an iterator:A general outline using a pointer as an iterator: Node_Type *iter; Node_Type *iter; for (iter = Head; iter != NULL; iter = iter->Link) for (iter = Head; iter != NULL; iter = iter->Link) //perform the action on the node iter //perform the action on the node iter

//points to //points to Head is a pointer to the head node of the listHead is a pointer to the head node of the list

Page 38: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 38

Iterator ExampleIterator Example

Using the previous outline of an iterator we Using the previous outline of an iterator we can display the contents of a linked list in thiscan display the contents of a linked list in thisway:way:

NodePtr iter;NodePtr iter; for (iter = Head; iter != NULL; for (iter = Head; iter != NULL;

iter = iter->Link)iter = iter->Link) cout << (iter->data); cout << (iter->data);

Page 39: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Inserting and Deleting in Locations Other Than the HeadObviously, it is a bit more difficult to insert an node at a point other than the head of a list.

We won't cover this as you will see these more sophisticated insertion and deletion routines for linked lists in a data structures class.

We will not cover the rest of Chapter 13 from the middle of page 749 on.

Page 40: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 40

Assignment With Pointers- A Assignment With Pointers- A CautionCaution

If head1 and head2 are pointer variables and If head1 and head2 are pointer variables and head1 points to the head node of a list:head1 points to the head node of a list: head2 = head1; head2 = head1;causes head2 and head1 to point to the same causes head2 and head1 to point to the same listlist There is only one list!There is only one list!

If you want head2 to point to a separate copy,If you want head2 to point to a separate copy,you must copy the list, node by node, oryou must copy the list, node by node, oroverload the assignment operator appropriatelyoverload the assignment operator appropriately

Page 41: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Many other data structures can be constructed Many other data structures can be constructed using nodes and pointersusing nodes and pointers

Doubly-Linked ListsDoubly-Linked Lists Each node has two links, one to the next node Each node has two links, one to the next node

and one to the previous nodeand one to the previous node Allows easy traversal of the list in both Allows easy traversal of the list in both

directionsdirections Often used in graphics programs - i.e. Often used in graphics programs - i.e.

scanning algorithmsscanning algorithms

Variations on Linked ListsVariations on Linked Lists

Slide 13- 41

Page 42: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Doubly-Linked ListDoubly-Linked List

struct Nodestruct Node

{{

int data;int data;

Node *forward_link;Node *forward_link;

Node *back_link;Node *back_link;

};};

Page 43: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Page 44: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

A A tree tree is a data structure that looks like an is a data structure that looks like an upside-down tree with the root at the topupside-down tree with the root at the top No cyclesNo cycles

In a binary tree each node has at most two linksIn a binary tree each node has at most two links

Binary TreeBinary Tree

Slide 13- 44

struct TreeNode{ int data;

TreeNode *left_link; TreeNode *right_link;};

Page 45: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Page 46: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

The preceding examples created linked The preceding examples created linked lists of structs. We can also create linked lists of structs. We can also create linked lists using classes.lists using classes.

The logic to use a class is identical except The logic to use a class is identical except the syntax of using and defining a class the syntax of using and defining a class should be substituted in place of that for a should be substituted in place of that for a structstruct

Linked List of ClassesLinked List of Classes

Slide 13- 46

Page 47: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 47

Section 13.1 ConclusionSection 13.1 Conclusion

Can youCan you Write type definitions for the nodes and Write type definitions for the nodes and

pointers in a linked list? Call the node pointers in a linked list? Call the node type NodeType and call the pointer type type NodeType and call the pointer type PointerType. The linked lists will be lists PointerType. The linked lists will be lists of letters.of letters.

Explain why inserting into an array can Explain why inserting into an array can be less efficient than inserting into a be less efficient than inserting into a linked list?linked list?

Page 48: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

13.213.2Stacks and QueuesStacks and Queues

(skipped as these are (skipped as these are covered in data structures)covered in data structures)

Page 49: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.

Slide 13- 49

Chapter 13 -- EndChapter 13 -- End