1 data structures chapter 15 2 what you will learn lists queues trees stacks

44
1 Data Structures Chapter 15

Upload: ginger-holmes

Post on 31-Dec-2015

217 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

1

Data Structures

Chapter 15

Page 2: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

2

What You Will LearnListsLists

QueuesQueues

TreesTrees

StacksStacks

Page 3: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

3

Introduction

Previously used fixed sized data structuresarraysstructs

Now we will use dynamic data structuresthey will grow and shrink during execution

Examplesstacksqueuesbinary trees

Page 4: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

4

Self-Referential Classes

A self-referential class contains a pointer member that points to a class object of the same class type

class Part_node { public: Part_node ( ); … private: char part_num[8], descrip[20]; int qty; float price; Part_node *next_part; } ;

class Part_node { public: Part_node ( ); … private: char part_num[8], descrip[20]; int qty; float price; Part_node *next_part; } ;

Page 5: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

5

Self-Referential Classes

This pointer to an object of the type being declared enables class objects to be linked together in various waysThis is how we get linked lists, stacks, queues

0

Pointervariable

LinkPointerMember

NullPointer

Page 6: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

6

Dynamic Memory Allocation

If the data structures are to be dynamic, then dynamic memory allocation is requiredoperators new and delete are essential

part_node *newPtr = new part_node; part_node *newPtr = new part_node;

Creates thenew pointer Allocates the space for

a new part node

0

Page 7: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

7

Dynamic Memory Allocation

The delete operator deallocates memory allocated with the new

Note: newPtr is not itself deleted -- rather the space newPtr points to

0

delete newPtr; delete newPtr;

Page 8: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

8

Linked Lists

Definition <=> A list of self-referential class objectscalled nodesconnected by pointer links (thus, a "linked" list)

Subsequent nodes accessed via link-pointer member stored in each member

Link pointer in last node set to null (zero)marks the end of the list

Nodes created dynamically, as needed

Page 9: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

9

Lists and Linked Lists

Criteria for choosing linked listmust be linear, homogeneous data

rules out sets & records

ordering does not depend on time of insertionrules out FIFO, LIFO

sequential access is sufficientrules out need for array

frequent insert, delete and requirement for sorting

Page 10: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

10

Linked List

Collection of structs (called nodes)One member is the data memberAt least one other member of the struct gives

location of next member This makes it self referential

head

77 -3

/

-3

/

44

Page 11: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

11

Linked List

Nodes do not necessarily occupy consecutive memory locations

Two ways to implementDynamic data with pointers (this is what our text

is advocating)Also possible to use built in arrays

Page 12: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

12

Linked List

Abstractions that are implemented using built-in types

Im plem entation H ierarchy for a lis t AD T

B u ilt-in A rray

B u ilt-in D yn am icd a ta an d p o in te rs

B u ilt-in A rray

L in ked L is t

L is t

Page 13: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

13

Declaration for a Linked List

// Declarationstruct NodeType;typedef Nodetype* NodePtr;

struct NodeType{ SomeDataType data; NodePtr link; };NodePtr head;NodePtr visitPtr;

Forward (incomplete)declaration

Forward (incomplete)declaration

Completedeclaration

Completedeclaration

Page 14: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

14

Dynamic Allocation of List Nodes

// Allocate a new dynamic object

head = new NodeType;(*head).data = 345;

Newly allocated object is a struct with 2 members

345345

head

data

link

Page 15: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

15

Dynamic Allocation

(*head).data (*head) is pointer dereferencing .data is struct selection

Equivalent (and easier to use) head ->dataThus we could have said

head->data =345;

Page 16: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

16

Linking Nodes Together

Head->link refers to …Thus

head->link = new NodeTypewill allocate a second NodeType struct, pointed to by the link element of the first

Then think what happens ...head->link->data = 12;head->link->link = NULL;

345345

head

data

link

Page 17: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

17

Characteristics of Singly Linked Lists

In previous slide, head is a pointer only, not a node on the list

*head is the struct pointed to by the headhead->link or (*head).link is the address of the

second struct*(head->link) or *((*head).link) is the entire

second structhead->link->data is the data member of the

second struct

Page 18: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

18

Constructing a List

Algorithmhead = new NodeType;currentPtr = head;do { currentPtr->link = NULL; // do something with currentPtr->data if (! done) { currentPtr->link = new NodeType; currentPtr =currentPtr->link; } } while (! done);

Page 19: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

19

Constructing List (version 2)ReadCities (/*out*/ CityPtr& cityList){CityPtr inNode;CityName tempName;cityList = Null;while (cin >> tempName) { inNode = new CityNode; strcpy (inNode->name, tempName); cin >> inNode->population; cin >> inNode->numVoters; inNode->next = cityList; cityList = inNode; }}

ReadCities (/*out*/ CityPtr& cityList){CityPtr inNode;CityName tempName;cityList = Null;while (cin >> tempName) { inNode = new CityNode; strcpy (inNode->name, tempName); cin >> inNode->population; cin >> inNode->numVoters; inNode->next = cityList; cityList = inNode; }}

Page 20: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

20

Constructing a List (Version 2)

inNodeinNode

cityListcityList

Longview

75

50

NULL

Page 21: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

21

Constructing a List (Version 2)

inNodeinNode

cityListcityList

Longview

75

50

NULL

Tyler

80

60

Page 22: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

22

Constructing a List (Version 2)

inNodeinNode

cityListcityList

Longview

75

50

NULL

Tyler

80

60

Dallas

1000

500

Page 23: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

23

Constructing a List (Version 2)

inNodeinNode

cityListcityList

Longview

75

50

NULL

Tyler

80

60

Dallas

1000

500

Hallsville

2

1

(Remember this is a reference parameter)

Page 24: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

24

Traversing a List

General algorithm

visitPtr = head;while (visitPtr != NULL) { // do something with the visitPtr -> data visitPtr = visitPtr -> link;}

Page 25: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

25

Recursive List Traversal

Recursive routinevoid visit_list ( /* in */ visit_ptr NodePtr) { if (visit_ptr != NULL) { visit_list (visit_ptr->link); cout << visit_ptr -> data; } }

Note that data is printed in reverse order of original input

Recursive Call

Recursive Call

Page 26: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

26

Linked ListsManipulate pointers to insert links into the list

(here at the beginning of the list)First store address of block with 7 in new

blockThen change contents of firstPtr to point to

the block with the 12

Page 27: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

27

Insertions

Assume we wish to insert a node with address insPtr between two other nodes already linked (the virst at prevPtr)

insPtr-> link = prevPtr-> link;prev_ptr->link = insPtr;

insPtrinsPtr

prevPtrprevPtr

Page 28: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

28

Linked Lists - Removing Nodes

Create tempPtr pointing to 1st nodeChange where firstPtr points to (2nd node in

list)Delete node pointed to by tempPtr

Before

After

Page 29: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

29

Deletions

Assume delete node after link pointed to by prevPtrtempPtr = prevPtr->link;prevPtr->link = tempPtr->link;delete tempPtr; // deallocates memory

prevPtr

tempPtr

Page 30: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

30

Linked Lists

Node can contain data of any typeConsider nodes with base class pointers

can have a linked list of derived objectsuse virtual function calls to process different

objects polymorphically

Other related structuresstacks, queues are constrained versions of linked

lists (they are linear)trees are non linear data structures

Page 31: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

31

Linked Lists

Advantages of linked lists (over arrays)when number of data elements in a list is unpredictablesize of conventional array in C++ is fixed

Can be maintained n sorted order by inserting new elements at proper point in listsimply a matter of adjusting pointers

Need not be contiguously stored in memoryare only contiguous logically

Note figure 15.3, pg 746 -- text CD audio

Page 32: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

32

Disadvantages of Dynamic Linked List

Algorithms sometimes more complex, harder to readharder to debug

Pointer space must be considered overheadespecially expensive when data portion of node is

small

Allocation, deallocation requires run-time overhead

Page 33: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

33

Head Nodes

First node is a special casepointed to by head pointernot pointed to by another noderequires special case algorithm

Can be solved by having a special “head node”pointed to by head pointerhas null datanext node has actual data

Page 34: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

34

Doubly Linked Lists

Minimize need for list traversalsHas two link members

one to next nodeanother to previous node

Wherever you are in the list, you can go either forward or backward to find the desired nodeinstead of always traversing from head for each

search

Page 35: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

35

Circular Linked Lists

Nodes identical to singly linked listPointer of last node always points to first

node(as does the head pointer)

head

77 -3-344

Page 36: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

36

Circular Linked List

Useful when no particular first or last itemHead pointer could point at any node

Logically the list is still the same

Special case processing when circular linked list is emptysolved by having a special “head node”

Page 37: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

37

473

Add Remove

Stacks

Constrained version of a linked listNew nodes can be added to or removed from

the list only at the top (front) of the listReferred to as last in, first out structure

LIFO

Page 38: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

38

The functions which accomplish addition to and removal from are referred to aspushpop

Stacks

473

s.Push (4) cout << s.Pop()

Stack s

7373 4

Page 39: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

39

Stacks -- Applications

Programming language keeps a stack of functions calledfunctions call other functions, etc.

Stacks contain space created for automatic variables on each function invocation

Used by compilers in processing evaluations of expressions

Note : we can use a Linked list class to implement a Stack class

See the StackExample Fig 15.9

on CD Rom

See the StackExample Fig 15.9

on CD Rom

Page 40: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

40

Queues

Another constricted linked list -- the list can be added to only at the end and deleted from only at the beginningFirst In - First Out … FIFO

The insert (or add) is known as the enqueue function

The remove (or delete) is known as the dequeue

Page 41: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

41

Queues -- Applications

For keeping track of multiple users on a single computer

To support printing -- many print jobs, one printerHandling information packets in networksFile server in a computer network

Note example in Figure 15.12, pg 763Listen to text CD audio

Page 42: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

42

Trees

Nonlinear, two dimensional data structurecontrast to lists, stacks, queues

Every node contains two (or multiple) links

Each link in root node refers to a child (there will be a right and left child)

Page 43: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

43

Trees

Note the double pointers in each nodeEnd nodes called leaf nodesFirst node called root node

Page 44: 1 Data Structures Chapter 15 2 What You Will Learn Lists Queues Trees Stacks

44

TreesBinary search tree

no duplicated node valuesvalues in any left sub tree are less than value in

parent nodevalues in any right sub tree are greater than value

in parent nodeNote Fig 15.16

hear text CD audioNote Fig 15.16

hear text CD audio