Date post: | 31-Dec-2015 |
Category: |
Documents |
Upload: | ginger-holmes |
View: | 217 times |
Download: | 3 times |
1
Data Structures
Chapter 15
2
What You Will LearnListsLists
QueuesQueues
TreesTrees
StacksStacks
3
Introduction
Previously used fixed sized data structuresarraysstructs
Now we will use dynamic data structuresthey will grow and shrink during execution
Examplesstacksqueuesbinary trees
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; } ;
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
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
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;
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
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
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
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
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
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
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
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;
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
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
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);
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; }}
20
Constructing a List (Version 2)
inNodeinNode
cityListcityList
Longview
75
50
NULL
21
Constructing a List (Version 2)
inNodeinNode
cityListcityList
Longview
75
50
NULL
Tyler
80
60
22
Constructing a List (Version 2)
inNodeinNode
cityListcityList
Longview
75
50
NULL
Tyler
80
60
Dallas
1000
500
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)
24
Traversing a List
General algorithm
visitPtr = head;while (visitPtr != NULL) { // do something with the visitPtr -> data visitPtr = visitPtr -> link;}
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
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
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
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
29
Deletions
Assume delete node after link pointed to by prevPtrtempPtr = prevPtr->link;prevPtr->link = tempPtr->link;delete tempPtr; // deallocates memory
prevPtr
tempPtr
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
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
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
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
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
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
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”
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
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
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
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
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
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)
43
Trees
Note the double pointers in each nodeEnd nodes called leaf nodesFirst node called root node
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