1 Chapter 3 Arrays, Linked Lists, and Recursion. 2 Static vs. Dynamic Structures A static data...

52
1 Chapter 3 Chapter 3 Arrays, Linked Lists, and Arrays, Linked Lists, and Recursion Recursion
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    222
  • download

    1

Transcript of 1 Chapter 3 Arrays, Linked Lists, and Recursion. 2 Static vs. Dynamic Structures A static data...

11

Chapter 3Chapter 3Arrays, Linked Lists, and RecursionArrays, Linked Lists, and Recursion

22

Static vs. Dynamic StructuresStatic vs. Dynamic StructuresA A staticstatic data structure has a fixed size data structure has a fixed size

This meaning is different than those This meaning is different than those associated with the associated with the staticstatic modifier modifier

Arrays are static; once you define the number Arrays are static; once you define the number of elements it can hold, it doesn’t changeof elements it can hold, it doesn’t change

A A dynamicdynamic data structure grows and shrinks data structure grows and shrinks as required by the information it containsas required by the information it contains

33

PreliminariesPreliminaries

Options for implementing an ADTOptions for implementing an ADT ArrayArray

Has a fixed sizeHas a fixed size

Data must be shifted during insertions and Data must be shifted during insertions and deletionsdeletions

Linked listLinked listIs able to grow in size as neededIs able to grow in size as needed

Does not require the shifting of items during Does not require the shifting of items during insertions and deletionsinsertions and deletions

44

Object ReferencesObject References

Recall that an Recall that an object referenceobject reference is a is a variable that stores the address of an variable that stores the address of an objectobject

A reference can also be called a A reference can also be called a pointerpointer

They are often depicted graphically:They are often depicted graphically:student

John Smith407253.57

55

Object ReferencesObject References

Figure 4.3a-dFigure 4.3a-da) Declaring reference

variables; b) allocating an

object; c) allocating another

object, with the dereferenced

object marked for garbage

collection

66

References as LinksReferences as Links

Object references can be used to create Object references can be used to create linkslinks between objects between objects

Suppose a Suppose a StudentStudent class contained a class contained a reference to another reference to another StudentStudent object object

John Smith407253.57

Jane Jones588213.72

77

References as LinksReferences as Links

References can be used to create a variety References can be used to create a variety of linked structures, such as a of linked structures, such as a linked listlinked list::studentList

88

PreliminariesPreliminaries

Figure 4.1Figure 4.1

a) A linked list of integers; b) insertion; c) deletion

99

Object ReferencesObject References

An array of objectsAn array of objects Is actually an array of references to the Is actually an array of references to the

objectsobjects ExampleExample

Integer[] scores = new Integer[30];Integer[] scores = new Integer[30];

Instantiating Integer objects for each array Instantiating Integer objects for each array referencereference

scores[0] = new Integer(7);scores[0] = new Integer(7);

scores[1] = new Integer(9); // and so on …scores[1] = new Integer(9); // and so on …

1010

Object ReferencesObject References

Equality operators (Equality operators (==== and and !=!=)) Compare the values of the reference variables, not Compare the values of the reference variables, not

the objects that they referencethe objects that they reference

equalsequals method method Compares objects field by fieldCompares objects field by field

When an object is passed to a method as an When an object is passed to a method as an argument, the reference to the object is copied argument, the reference to the object is copied to the method’s formal parameterto the method’s formal parameterReference-based ADT implementations and Reference-based ADT implementations and data structures use Java references data structures use Java references

1111

Resizable ArraysResizable Arrays

The number of references in a Java array is of The number of references in a Java array is of fixed sizefixed sizeResizable arrayResizable array An array that grows and shrinks as the program An array that grows and shrinks as the program

executesexecutes An illusion that is created by using an allocate and An illusion that is created by using an allocate and

copy strategy with fixed-size arrayscopy strategy with fixed-size arrays

java.util.Vectorjava.util.Vector class class Uses a similar technique to implement a growable Uses a similar technique to implement a growable

array of objectsarray of objects

1212

Reference-Based Linked ListsReference-Based Linked Lists

Linked listLinked list Contains nodes that are linked to Contains nodes that are linked to

one anotherone another A nodeA node

Contains both data and a “link” to the Contains both data and a “link” to the next itemnext itemCan be implemented as an objectCan be implemented as an object

public class Node {public class Node { private Object item;private Object item; private Node next;private Node next; // constructors, accessors, // constructors, accessors,

// and mutators …// and mutators …} // end class Node} // end class Node

Figure 4.5Figure 4.5

A node

1313

Reference-Based Linked ListsReference-Based Linked ListsUsing the Node classUsing the Node class

Node n = new Node (new Integer(6));Node n = new Node (new Integer(6));Node first = new Node (new Integer(9), n);Node first = new Node (new Integer(9), n);

Figure 4.7Figure 4.7

Using the Node constructor to initialize a data field and a link value

1414

Reference-Based Linked ListsReference-Based Linked Lists

Data field Data field nextnext in the last node is set to in the last node is set to nullnullheadhead reference variable reference variable References the list’s first nodeReferences the list’s first node Always exists even when the list is emptyAlways exists even when the list is empty

Figure 4.8Figure 4.8

A head reference to a linked list

1515

Reference-Based Linked ListsReference-Based Linked Lists

headhead reference variable can be assigned reference variable can be assigned nullnull without without first using first using newnew

Following sequence results in a lost nodeFollowing sequence results in a lost nodehead = new Node(); // Don’t really need to use new herehead = new Node(); // Don’t really need to use new here

head = null; // since we lose the new Node object herehead = null; // since we lose the new Node object here

Figure 4.9Figure 4.9

A lost node

1616

Programming with Linked Lists:Programming with Linked Lists:Displaying the Contents of a Displaying the Contents of a

Linked ListLinked Listcurrcurr reference variable reference variable References the current nodeReferences the current node Initially references the first nodeInitially references the first node

To display the data portion of the current nodeTo display the data portion of the current nodeSystem.out.println(curr.getItem());System.out.println(curr.getItem());

To advance the current position to the next nodeTo advance the current position to the next nodecurr = curr.getNext();curr = curr.getNext();

1717

Displaying the Contents of a Displaying the Contents of a Linked ListLinked List

Figure 4.10Figure 4.10

The effect of the assignment curr = curr.getNext( )

1818

Displaying the Contents of a Displaying the Contents of a Linked ListLinked List

To display all the data items in a linked listTo display all the data items in a linked listfor (Node curr = head; curr != null; curr = for (Node curr = head; curr != null; curr =

curr.getNext()) { curr.getNext()) {

System.out.println(curr.getItem());System.out.println(curr.getItem());

} // end for} // end for

1919

Deleting a Specified Node from Deleting a Specified Node from a Linked Lista Linked List

To delete node N which To delete node N which currcurr references references Set Set nextnext in the node that precedes N to reference the node that in the node that precedes N to reference the node that

follows N follows N prev.setNext(curr.getNext());prev.setNext(curr.getNext());

Figure 4.11Figure 4.11

Deleting a node from a linked list

2020

Deleting a Specified Node from Deleting a Specified Node from a Linked Lista Linked List

Deleting the first node is a special caseDeleting the first node is a special casehead = head.getNext();head = head.getNext();

Figure 4.12Figure 4.12

Deleting the first node

2121

Inserting a Node into a Inserting a Node into a Specified Position of a Linked Specified Position of a Linked

ListListTo create a node for the new itemTo create a node for the new item

newNode = new Node(item);newNode = new Node(item);

To insert a node between two nodesTo insert a node between two nodesnewNode.setNext(curr);newNode.setNext(curr);prev.setNext(newNode);prev.setNext(newNode);

Figure 4.13Figure 4.13

Inserting a new node into a linked list

2222

Inserting a Node into a Inserting a Node into a Specified Position of a Linked Specified Position of a Linked

ListListTo insert a node at the beginning of a linked listTo insert a node at the beginning of a linked list

newNode.setNext(head);newNode.setNext(head);

head = newNode;head = newNode;

Figure 4.14Figure 4.14

Inserting at the beginning of a linked list

2323

Inserting a Node into a Inserting a Node into a Specified Position of a Linked Specified Position of a Linked

ListListInserting at the end of a linked list is not a special Inserting at the end of a linked list is not a special case if case if currcurr is is nullnull

newNode.setNext(curr);newNode.setNext(curr);prev.setNext(newNode);prev.setNext(newNode);

Figure 4.15Figure 4.15

Inserting at the end of

a linked list

2424

Inserting a Node into a Inserting a Node into a Specified Position of a Linked Specified Position of a Linked

ListListThree steps to insert a new node into a Three steps to insert a new node into a linked listlinked list Determine the point of insertionDetermine the point of insertion Create a new node and store the new data in Create a new node and store the new data in

itit Connect the new node to the linked list by Connect the new node to the linked list by

changing referenceschanging references

2525

Determining Determining currcurr and and prevprev

Determining the point of insertion or deletion for a sorted Determining the point of insertion or deletion for a sorted linked list of objectslinked list of objects

for ( prev = null, curr = head;for ( prev = null, curr = head;

(curr != null) && (curr != null) &&

(newValue.compareTo(curr.getItem()) > (newValue.compareTo(curr.getItem()) > 0);0);

prev = curr, curr = curr.getNext() ) {prev = curr, curr = curr.getNext() ) {

} // end for} // end for

2626

A Reference-Based A Reference-Based Implementation of the ADT ListImplementation of the ADT ListA reference-based implementation of the ADT listA reference-based implementation of the ADT list Does not shift items during insertions and deletionsDoes not shift items during insertions and deletions Does not impose a fixed maximum length on the list Does not impose a fixed maximum length on the list

Figure 4.18Figure 4.18

A reference-based implementation of the ADT list

2727

Comparing Array-Based and Comparing Array-Based and Referenced-Based Referenced-Based ImplementationsImplementations

SizeSize Array-basedArray-based

Fixed sizeFixed size IssuesIssues

Can you predict the maximum number of items in the Can you predict the maximum number of items in the ADT?ADT?

Will an array waste storage?Will an array waste storage? Resizable arrayResizable array

Increasing the size of a resizable array can waste Increasing the size of a resizable array can waste storage and timestorage and time

2828

Comparing Array-Based and Comparing Array-Based and Referenced-Based Referenced-Based ImplementationsImplementations

Size (Continued)Size (Continued) Reference-basedReference-based

Do not have a fixed sizeDo not have a fixed size Do not need to predict the maximum size of the listDo not need to predict the maximum size of the list Will not waste storageWill not waste storage

Storage requirementsStorage requirements Array-basedArray-based

Requires less memory than a reference-based Requires less memory than a reference-based implementationimplementation

There is no need to store explicitly information about where to There is no need to store explicitly information about where to find the next data itemfind the next data item

2929

Comparing Array-Based and Comparing Array-Based and Referenced-Based Referenced-Based ImplementationsImplementations

Storage requirements (Continued)Storage requirements (Continued) Reference-basedReference-based

Requires more storageRequires more storage An item explicitly references the next item in the listAn item explicitly references the next item in the list

Access timeAccess time Array-basedArray-based

Constant access timeConstant access time Reference-basedReference-based

The time to access the iThe time to access the ithth node depends on i node depends on i

3030

Comparing Array-Based and Comparing Array-Based and Referenced-Based Referenced-Based ImplementationsImplementations

Insertion and deletionsInsertion and deletions Array-basedArray-based

Require you to shift the dataRequire you to shift the data Reference-basedReference-based

Do not require you to shift the dataDo not require you to shift the data

Require a list traversalRequire a list traversal

3131

Passing a Linked List to a Passing a Linked List to a MethodMethod

A method with access to a linked list’s A method with access to a linked list’s headhead reference reference has access to the entire listhas access to the entire listWhen head is an actual argument to a method, its value When head is an actual argument to a method, its value is copied into the corresponding formal parameteris copied into the corresponding formal parameter

Figure 4.19Figure 4.19

A head reference as an argument

3232

Processing Linked List Processing Linked List RecursivelyRecursively

TraversalTraversal Recursive strategy to display a listRecursive strategy to display a list

Write the first node of the listWrite the first node of the list

Write the list minus its first nodeWrite the list minus its first node Recursive strategies to display a list backward Recursive strategies to display a list backward

writeListBackwardwriteListBackward strategy strategyWrite the last node of the listWrite the last node of the listWrite the list minus its last node backwardWrite the list minus its last node backward

writeListBackward2writeListBackward2 strategy strategyWrite the list minus its first node backwardWrite the list minus its first node backwardWrite the first node of the listWrite the first node of the list

3333

Processing Linked List Processing Linked List RecursivelyRecursively

InsertionInsertion Recursive view of a sorted linked listRecursive view of a sorted linked list

The linked list that The linked list that headhead references is a sorted linked list if references is a sorted linked list if

headhead is is nullnull (the empty list is a sorted linked list) (the empty list is a sorted linked list)

oror

head.getNext()head.getNext() is is nullnull (a list with a single node is a (a list with a single node is a

sorted linked list)sorted linked list)

oror

head.getItem() < head.getNext().getItem()head.getItem() < head.getNext().getItem(),,

and and head.getNext()head.getNext() references a sorted linked list references a sorted linked list

3434

Variations of the Linked List:Variations of the Linked List:Tail ReferencesTail References

tailtail reference reference Remembers where the end of the linked list isRemembers where the end of the linked list is To add a node to the end of a linked listTo add a node to the end of a linked list

tail.setNext(new Node(request, null));tail.setNext(new Node(request, null));

Figure 4.22Figure 4.22

A linked list with head and tail references

3535

Circular Linked ListCircular Linked List

Last node references the first nodeLast node references the first node

Every node has a successorEvery node has a successor

Figure 4.23Figure 4.23

A circular linked list

3636

Circular Linked ListCircular Linked List

Figure 4.24Figure 4.24

A circular linked list with an external reference to the last node

3737

Doubly Linked ListDoubly Linked List

Each node references both its predecessor and its Each node references both its predecessor and its successorsuccessor

Figure 4.27Figure 4.27

A doubly linked list

3838

Doubly Linked ListDoubly Linked List

Circular doubly linked listCircular doubly linked list precedeprecede reference of the head node reference of the head node

references the last nodereferences the last node nextnext reference of the last node references reference of the last node references

the head nodethe head node Eliminates special cases for insertions and Eliminates special cases for insertions and

deletionsdeletions

3939

Doubly Linked ListDoubly Linked ListTo delete the node that To delete the node that currcurr references referencescurr.getPrecede().setNext(curr.getNext());curr.getPrecede().setNext(curr.getNext());

curr.getNext().setPrecede(curr.getPrecede());curr.getNext().setPrecede(curr.getPrecede());

Figure 4.29Figure 4.29

Reference changes for deletion

4040

Doubly Linked ListDoubly Linked ListTo insert a new node that To insert a new node that newNodenewNode references before references before the node referenced by the node referenced by currcurr newNode.setNext(curr);newNode.setNext(curr);newNode.setPrecede(curr.getPrecede());newNode.setPrecede(curr.getPrecede());curr.setPrecede(newNode);curr.setPrecede(newNode);newNode.getPrecede().setNext(newNode);newNode.getPrecede().setNext(newNode);

Figure 4.30Figure 4.30

Reference changes

for insertion

4141

SummarySummary

Reference variables can be used to Reference variables can be used to implement the data structure known as a implement the data structure known as a linked listlinked list

Each reference in a linked list is a reference Each reference in a linked list is a reference to the next node in the listto the next node in the list

Algorithms for insertions and deletions in a Algorithms for insertions and deletions in a linked list involvelinked list involve Traversing the list from the beginning until you Traversing the list from the beginning until you

reach the appropriate positionreach the appropriate position Performing reference changes to alter the Performing reference changes to alter the

structure of the list structure of the list

4242

SummarySummaryInserting a new node at the beginning of a Inserting a new node at the beginning of a linked list and deleting the first node of a linked linked list and deleting the first node of a linked list are special caseslist are special casesAn array-based implementation uses an An array-based implementation uses an implicit ordering scheme; a reference-based implicit ordering scheme; a reference-based implementation uses an explicit ordering implementation uses an explicit ordering schemeschemeAny element in an array can be accessed Any element in an array can be accessed directly; you must traverse a linked list to directly; you must traverse a linked list to access a particular nodeaccess a particular nodeItems can be inserted into and deleted from a Items can be inserted into and deleted from a reference-based linked list without shifting datareference-based linked list without shifting data

4343

SummarySummary

The The newnew operator can be used to allocate operator can be used to allocate memory dynamically for both an array and a memory dynamically for both an array and a linked listlinked list The size of a linked list can be increased one node at The size of a linked list can be increased one node at

a time more efficiently than that of an arraya time more efficiently than that of an array

A binary search of a linked list is impracticalA binary search of a linked list is impracticalRecursion can be used to perform operations on Recursion can be used to perform operations on a linked lista linked listThe recursive insertion algorithm for a sorted The recursive insertion algorithm for a sorted linked list works because each smaller linked list linked list works because each smaller linked list is also sortedis also sorted

4444

SummarySummary

A tail reference can be used to facilitate locating the A tail reference can be used to facilitate locating the end of a listend of a listIn a circular linked list, the last node references the In a circular linked list, the last node references the first nodefirst nodeDummy head nodes eliminate the special cases for Dummy head nodes eliminate the special cases for insertion into and deletion from the beginning of a insertion into and deletion from the beginning of a linked listlinked listA head record contains global information about a A head record contains global information about a linked listlinked listA doubly linked list allows you to traverse the list in A doubly linked list allows you to traverse the list in either directioneither direction

4545

Recursive ThinkingRecursive ThinkingA A recursive definitionrecursive definition is one which uses the is one which uses the word or concept being defined in the definition word or concept being defined in the definition itselfitself

When defining an English word, a recursive When defining an English word, a recursive definition is often not helpful – “When a person definition is often not helpful – “When a person is hungry it means they are hungry”.is hungry it means they are hungry”.

But in other situations, a recursive definition But in other situations, a recursive definition can be an appropriate way to express a can be an appropriate way to express a conceptconcept

4646

Recursive DefinitionsRecursive Definitions

Consider the following list of numbers:Consider the following list of numbers:

24, 88, 40, 3724, 88, 40, 37

Such a list can be defined asSuch a list can be defined as

A LIST is a: numberA LIST is a: number or a: number comma LISTor a: number comma LIST

That is, a LIST is defined to be a single number, or a That is, a LIST is defined to be a single number, or a number followed by a comma followed by a LISTnumber followed by a comma followed by a LIST

The concept of a LIST is used to define itselfThe concept of a LIST is used to define itself

4747

Infinite RecursionInfinite Recursion

All recursive definitions MUST have a non-All recursive definitions MUST have a non-recursive partrecursive part

Otherwise you’d get Otherwise you’d get infinite recursioninfinite recursion

The non-recursive part is often called the The non-recursive part is often called the base base casecase

A LIST (of numbers) is defined to be:A LIST (of numbers) is defined to be:a: numbera: number (base case)(base case)

or or a: number comma LISTa: number comma LIST (recursive (recursive

part)part)

4848

Recursive ProgrammingRecursive ProgrammingA method in Java can invoke itself; if it does then it is called a A method in Java can invoke itself; if it does then it is called a recursive methodrecursive method

If a method does invoke itself, at some point its got to stop it! If a method does invoke itself, at some point its got to stop it! Otherwise it will invoke itself “forever”! The end result of infinite Otherwise it will invoke itself “forever”! The end result of infinite recursion is that your program will run out of memory. recursion is that your program will run out of memory.

Even though the method is invoking itself, the local (method) data Even though the method is invoking itself, the local (method) data associated with each invocation is unique. associated with each invocation is unique.

As always, when the method completes, control returns to the As always, when the method completes, control returns to the method that invoked it (which may be an earlier invocation of itself)method that invoked it (which may be an earlier invocation of itself)

4949

Indirect RecursionIndirect Recursion

A method invoking itself is considered to be A method invoking itself is considered to be direct recursiondirect recursion

A method could invoke another method, which invokes another, etc., until A method could invoke another method, which invokes another, etc., until eventually the original method is invoked againeventually the original method is invoked again

For example, method For example, method m1m1 could invoke could invoke m2m2, which invokes , which invokes m3m3, which in turn , which in turn invokes invokes m1m1 again again

This is called This is called indirect recursionindirect recursion, and requires all the same care as direct , and requires all the same care as direct recursionrecursion

It is often more difficult to trace and debugIt is often more difficult to trace and debug

5050

Indirect RecursionIndirect Recursion

m1 m2 m3

m1 m2 m3

m1 m2 m3

5151

Recursive ProgrammingRecursive ProgrammingJust because we can use recursion to solve a problem, it doesn't mean we Just because we can use recursion to solve a problem, it doesn't mean we should.should.

For instance, we usually would not use recursion to solve the sum of 1 to N For instance, we usually would not use recursion to solve the sum of 1 to N problem, because the iterative version is easier to understandproblem, because the iterative version is easier to understand

There are other reasons to NOT use recursion – efficiency (time, space) being There are other reasons to NOT use recursion – efficiency (time, space) being one of the big ones. General rule: recursion is slower (sometimes much slower, one of the big ones. General rule: recursion is slower (sometimes much slower, or “dog slow” in programmer vernacular) than a well-coded iterative approach.or “dog slow” in programmer vernacular) than a well-coded iterative approach.

However, for some problems, recursion provides an elegant solution, often However, for some problems, recursion provides an elegant solution, often cleaner than an iterative versioncleaner than an iterative version

You must carefully decide whether recursion is the correct technique for any You must carefully decide whether recursion is the correct technique for any problemproblem

One of the most important elements to consider is the MAXIMUM expected One of the most important elements to consider is the MAXIMUM expected stack depthstack depth

5252