Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna...

52
Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by Pearson Education / Addison-Wesley. Copyright © 2007 Pearson Addison-Wesley Copyright © 2013 Aiman Hanna All rights reserved

Transcript of Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna...

Page 1: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Comp 249 Programming Methodology

Chapter 15Linked Data Structure – Part A

Dr. Aiman HannaDepartment of Computer Science & Software Engineering

Concordia University, Montreal, Canada

These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by

Pearson Education / Addison-Wesley.

Copyright © 2007 Pearson Addison-WesleyCopyright © 2013 Aiman Hanna

All rights reserved

Page 2: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Introduction to Linked Data Introduction to Linked Data StructuresStructures

A A linked data structurelinked data structure consists of capsules of consists of capsules of data known as data known as nodesnodes that are connected via that are connected via linkslinks Links can be viewed as arrows and thought of as Links can be viewed as arrows and thought of as

one way passages from one node to anotherone way passages from one node to another In Java, nodes are realized as objects of a node In Java, nodes are realized as objects of a node

classclass The data in a node is stored via instance variablesThe data in a node is stored via instance variables The links are realized as referencesThe links are realized as references

A reference is a memory address, and is stored A reference is a memory address, and is stored in a variable of a class typein a variable of a class type

Therefore, a link is an instance variable of the Therefore, a link is an instance variable of the node class type itselfnode class type itself

15-2

Page 3: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Java Linked ListsJava Linked Lists

The simplest kind of linked data The simplest kind of linked data structure is a structure is a linked listlinked list

A linked list consists of a single A linked list consists of a single chain of nodes, each connected to chain of nodes, each connected to the next by a linkthe next by a link The first node is called the The first node is called the headhead node node The last node serves as a kind of end The last node serves as a kind of end

markermarker

15-3

Page 4: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Nodes and Links in a Nodes and Links in a Linked ListLinked List

15-4

Page 5: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Simple Linked List A Simple Linked List ClassClass

In a linked list, each node is an object of a node classIn a linked list, each node is an object of a node class Note that each node is typically illustrated as a box Note that each node is typically illustrated as a box

containing one or more pieces of datacontaining one or more pieces of data Each node contains data and a link to another nodeEach node contains data and a link to another node

A piece of data is stored as an instance variable of the nodeA piece of data is stored as an instance variable of the node Data is represented as information contained within the node Data is represented as information contained within the node

"box""box" Links are implemented as references to a node stored in an Links are implemented as references to a node stored in an

instance variable of the node typeinstance variable of the node type Links are typically illustrated as arrows that point to the Links are typically illustrated as arrows that point to the

node to which they "link“node to which they "link“

See LinkedList1.javaSee LinkedList1.javaSee LinkedList2.javaSee LinkedList2.java

15-5

Page 6: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Simple Linked List A Simple Linked List ClassClass

The first node, or start node in a linked The first node, or start node in a linked list is called the head nodelist is called the head node The entire linked list can be traversed by The entire linked list can be traversed by

starting at the head node and visiting each starting at the head node and visiting each node exactly oncenode exactly once

There is typically a variable of the node There is typically a variable of the node type (e.g., type (e.g., headhead) that contains a reference ) that contains a reference to the first node in the linked listto the first node in the linked list However, it is not the head node, nor is it even However, it is not the head node, nor is it even

a nodea node It simply contains a reference to the head It simply contains a reference to the head

nodenode

15-6

Page 7: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Simple Linked List A Simple Linked List ClassClass

A linked list object contains the variable A linked list object contains the variable headhead as an instance variable of the class as an instance variable of the class

A linked list object does not contain all A linked list object does not contain all the nodes in the linked list directlythe nodes in the linked list directly Rather, it uses the instance variable Rather, it uses the instance variable headhead to to

locate the head node of the listlocate the head node of the list The head node and every node of the list The head node and every node of the list

contain a link instance variable that provides a contain a link instance variable that provides a reference to the next node in the listreference to the next node in the list

Therefore, once the head node can be Therefore, once the head node can be reached, then every other node in the list can reached, then every other node in the list can be reached be reached

15-7

Page 8: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

An Empty List Is An Empty List Is Indicated by Indicated by nullnull

The The headhead instance variable contains a instance variable contains a reference to the first node in the linked reference to the first node in the linked listlist If the list is empty, this instance variable is set If the list is empty, this instance variable is set

to to nullnull Note: This is tested using Note: This is tested using ====, not the , not the equalsequals

methodmethod The linked list constructor sets the head The linked list constructor sets the head

instance variable to instance variable to nullnull This indicates that the newly created linked This indicates that the newly created linked

list is emptylist is empty

15-8

Page 9: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Indicating the End of a Indicating the End of a Linked ListLinked List

The last node in a linked list should The last node in a linked list should have its link instance variable set to have its link instance variable set to nullnull That way the code can test whether or That way the code can test whether or

not a node is the last nodenot a node is the last node Note: This is tested using Note: This is tested using ====, not the , not the equalsequals method method

15-9

Page 10: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Traversing a Linked ListTraversing a Linked List If a linked list already contains nodes, it If a linked list already contains nodes, it

can be traversed as follows:can be traversed as follows: Set a local variable equal to the value stored Set a local variable equal to the value stored

by the head node (its reference)by the head node (its reference) This will provides the location of the first nodeThis will provides the location of the first node After accessing the first node, the accessor After accessing the first node, the accessor

method for the link instance variable will method for the link instance variable will provide the location of the next nodeprovide the location of the next node

Repeat this until the location of the next node Repeat this until the location of the next node is equal to is equal to nullnull

15-10

Page 11: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Traversing a Linked ListTraversing a Linked List

15-11

Page 12: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Adding a Node at the Adding a Node at the StartStart

15-12

Page 13: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Deleting the Head Node from Deleting the Head Node from a Linked List a Linked List

The method The method deleteHeadNodedeleteHeadNode removes the removes the first node from the linked listfirst node from the linked list It leaves the It leaves the headhead variable pointing to (i.e., variable pointing to (i.e.,

containing a reference to) the old second node containing a reference to) the old second node in the linked listin the linked list

The deleted node will automatically be The deleted node will automatically be collected and its memory recycled, along collected and its memory recycled, along with any other nodes that are no longer with any other nodes that are no longer accessibleaccessible In Java, this process is called In Java, this process is called automatic automatic

garbage collectiongarbage collection

15-13

Page 14: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Pitfall: Privacy LeaksPitfall: Privacy Leaks You should be careful with privacy leak. You should be careful with privacy leak.

If the node class accessor method returns a If the node class accessor method returns a reference to a node, then the reference to a node, then the privateprivate restriction on the instance variables can be restriction on the instance variables can be easily defeatedeasily defeated

The easiest way to fix this problem would be to The easiest way to fix this problem would be to make the node class a private inner class in make the node class a private inner class in the linked list classthe linked list class

See LinkedList3.javaSee LinkedList3.java

15-14

Page 15: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Node Inner ClassesNode Inner Classes Note that the linked list class discussed so far is Note that the linked list class discussed so far is

dependent on an external node classdependent on an external node class A linked list or similar data structure can be made A linked list or similar data structure can be made

self-contained by making the node class an inner self-contained by making the node class an inner classclass

A node inner class so defined should be made A node inner class so defined should be made private, unless used elsewhereprivate, unless used elsewhere

This can simplify the definition of the node class by This can simplify the definition of the node class by eliminating the need for accessor and mutator methodseliminating the need for accessor and mutator methods

Since the instance variables are private, they can be Since the instance variables are private, they can be accessed directly from methods of the outer class without accessed directly from methods of the outer class without causing a privacy leakcausing a privacy leak

See LinkedList4.javaSee LinkedList4.java15-15

Page 16: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Linked Lists Copy Constructors Linked Lists Copy Constructors and and cloneclone Methods Methods

There is a simple way to define copy constructors There is a simple way to define copy constructors and the and the cloneclone method for data structures such as method for data structures such as linked listslinked lists Unfortunately, this approach produces only shallow Unfortunately, this approach produces only shallow

copiescopies

Further coding is needed by the programmer in Further coding is needed by the programmer in order to create copy constructor and clone() order to create copy constructor and clone() methods that perform deep copymethods that perform deep copy

See LinkedList5.javaSee LinkedList5.javaSee LinkedList6.javaSee LinkedList6.java

15-16

Page 17: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Generic Linked ListA Generic Linked List A linked list can be created whose A linked list can be created whose NodeNode class has a class has a type type

parameter parameter TT for the type of data stored in the node for the type of data stored in the node Therefore, it can hold objects of any class type, including types Therefore, it can hold objects of any class type, including types

that contain multiple instance variablethat contain multiple instance variable The type of the actual object is plugged in for the type The type of the actual object is plugged in for the type

parameter parameter TT

For the most part, this class can have the same For the most part, this class can have the same methods, coded in basically the same way, however methods, coded in basically the same way, however some major difference can be there, and adjustment to some major difference can be there, and adjustment to the code may hence be necessary the code may hence be necessary

One of such differences is the use of the clone() methodOne of such differences is the use of the clone() method

See LinkedList7.javaSee LinkedList7.javaSee LinkedList8.javaSee LinkedList8.java

15-17

Page 18: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Pitfall: The Pitfall: The cloneclone Method Is Method Is Protected in ObjectProtected in Object

It would have been preferable to clone the It would have been preferable to clone the data belonging to the list being copied in the data belonging to the list being copied in the copyOfcopyOf method as follows: method as follows:nodeReferencenodeReference = new = new

Node(Node((T)(T)(position.data).(position.data).clone()clone(), null);, null); However, this is not allowed, and this code However, this is not allowed, and this code

will not compilewill not compile The error message generated will state that The error message generated will state that cloneclone

is protected in is protected in ObjectObject Although the type used is Although the type used is TT, not , not ObjectObject, any class , any class

can be plugged in for can be plugged in for TT When the class is compiled, all that Java knows is When the class is compiled, all that Java knows is

that that TT is a descendent class of Object is a descendent class of Object

15-18

Page 19: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Tip: Use a Type Parameter Bound Tip: Use a Type Parameter Bound for a Better for a Better cloneclone

One solution to this problem is to One solution to this problem is to place a bound on the type parameter place a bound on the type parameter TT so that it must satisfy a suitable so that it must satisfy a suitable interfaceinterface

Although there is no standard interface Although there is no standard interface that does this, it is easy to define onethat does this, it is easy to define one

For example, a For example, a Cloneable2Cloneable2 interface interface could be definedcould be defined

15-19

Page 20: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Tip: Use a Type Parameter Bound Tip: Use a Type Parameter Bound for a Better for a Better cloneclone

Any class that implements the Any class that implements the Cloneable2Cloneable2 interface would have interface would have these three properties:these three properties:

1.1. It would implement the It would implement the CloneableCloneable interface because interface because Cloneable2 Cloneable2 extends extends CloneableCloneable

2.2. It would have to implement a public It would have to implement a public cloneclone method method

3.3. Its Its cloneclone method would have to make a method would have to make a deep copydeep copy

15-20

Page 21: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Tip: Cloning is an "All or Nothing" Tip: Cloning is an "All or Nothing" AffairAffair

If a If a cloneclone method is defined for a method is defined for a class, then it should follow the class, then it should follow the official Java guidelinesofficial Java guidelines In particular, it should implement the In particular, it should implement the CloneableCloneable interface interface

15-21

Page 22: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

ExceptionsExceptions A generic data structure is likely to have A generic data structure is likely to have

methods that throw exceptionsmethods that throw exceptions Situations such as a Situations such as a nullnull argument to the copy argument to the copy

constructor may be handled differently in constructor may be handled differently in different situationsdifferent situations If this happens, it is best to throw a If this happens, it is best to throw a NullPointerExceptionNullPointerException, and let the programmer who is , and let the programmer who is using the linked list handle the exception, rather than using the linked list handle the exception, rather than take some arbitrary actiontake some arbitrary action

A A NullPointerExceptionNullPointerException is an is an uncheckedunchecked exception: it exception: it need not be caught or declared in a throws clauseneed not be caught or declared in a throws clause

15-22

Page 23: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Pitfall: Using Pitfall: Using NodeNode instead of instead of Node<T>Node<T>

Any names can be substituted for the node Any names can be substituted for the node NodeNode and its parameter and its parameter <T><T>

When defining the When defining the List<T>List<T> class, the type for a class, the type for a node is node is Node<T>Node<T>, , notnot NodeNode If the If the <T><T> is omitted, this is an error for which the is omitted, this is an error for which the

compiler may or may not issue an error message compiler may or may not issue an error message (depending on the details of the code), and even if it (depending on the details of the code), and even if it does, the error message may be quite strangedoes, the error message may be quite strange

Look for a missing Look for a missing <T><T> when a program that uses when a program that uses nodes with type parameters gets a strange error nodes with type parameters gets a strange error message or doesn't run correctlymessage or doesn't run correctly

15-23

Page 24: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Generic Linked List: the A Generic Linked List: the equalsequals MethodMethod

Like other classes, a linked list class should Like other classes, a linked list class should normally have an normally have an equalsequals method method

The The equalsequals method can be defined in a number method can be defined in a number of reasonable ways of reasonable ways Different definitions may be appropriate for different Different definitions may be appropriate for different

situations situations Two such possibilities are the following:Two such possibilities are the following:

1.1. They contain the same data entries (possibly in They contain the same data entries (possibly in different orders)different orders)

2.2. They contain the same data entries in the same orderThey contain the same data entries in the same order

Of course, the type plugged in for Of course, the type plugged in for TT must also must also have redefined the have redefined the equalsequals method method

15-24

Page 25: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

IteratorsIterators A collection of objects, such as the nodes of a A collection of objects, such as the nodes of a

linked list, must often be traversed in order to linked list, must often be traversed in order to perform some action on each objectperform some action on each object An An iteratoriterator is any object that enables a list to be is any object that enables a list to be

traversed in this waytraversed in this way

A linked list class may be created that has an A linked list class may be created that has an iterator inner classiterator inner class If iterator variables are to be used outside the linked list If iterator variables are to be used outside the linked list

class, then the iterator class would be made publicclass, then the iterator class would be made public The linked list class would have an The linked list class would have an iteratoriterator method method

that returns an iterator for its calling objectthat returns an iterator for its calling object Given a linked list named Given a linked list named listlist, this can be done as , this can be done as

follows:follows: LinkedList2.List2Iterator i = list.iterator();LinkedList2.List2Iterator i = list.iterator();

15-25

Page 26: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

IteratorsIterators

The basic methods used by an iterator The basic methods used by an iterator are as follows:are as follows: restartrestart: Resets the iterator to the : Resets the iterator to the

beginning of the listbeginning of the list hasNexthasNext: Determines if there is another : Determines if there is another

data item on the listdata item on the list nextnext: Produces the next data item on the : Produces the next data item on the

listlist

See LinkedList9.javaSee LinkedList9.java

15-26

Page 27: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Linked List with A Linked List with an Iterator (Part 1 an Iterator (Part 1

of 6)of 6)

15-27

Page 28: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Linked List with A Linked List with an Iterator (Part 2 an Iterator (Part 2

of 6)of 6)

15-28

Page 29: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Linked List with A Linked List with an Iterator (Part 3 of an Iterator (Part 3 of

6)6)

15-29

Page 30: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Linked List with A Linked List with an Iterator (Part 4 an Iterator (Part 4

of 6)of 6)

15-30

Page 31: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Linked List with A Linked List with an Iterator (Part 5 of an Iterator (Part 5 of

6)6)

15-31

Page 32: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Linked List with A Linked List with an Iterator (Part 6 an Iterator (Part 6

of 6)of 6)

15-32

Page 33: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Using an Iterator (Part 1 Using an Iterator (Part 1 of 6)of 6)

15-33

Page 34: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Using an Iterator (Part 2 Using an Iterator (Part 2 of 6)of 6)

15-34

Page 35: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Using an Iterator (Part 3 Using an Iterator (Part 3 of 6)of 6)

15-35

Page 36: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Using an Iterator (Part 4 Using an Iterator (Part 4 of 6)of 6)

15-36

Page 37: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Using an Iterator (Part 5 Using an Iterator (Part 5 of 6)of 6)

15-37

Page 38: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Using an Iterator (Part 6 Using an Iterator (Part 6 of 6)of 6)

15-38

Page 39: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

The Java Iterator The Java Iterator InterfaceInterface

Java has an interface named Java has an interface named IteratorIterator that specifies how Java that specifies how Java would like an iterator to behavewould like an iterator to behave Although the iterators examined so far Although the iterators examined so far

do not satisfy this interface, they could do not satisfy this interface, they could be easily redefined to do sobe easily redefined to do so

15-39

Page 40: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Adding and Deleting Adding and Deleting NodesNodes

An iterator is normally used to add or An iterator is normally used to add or delete a node in a linked listdelete a node in a linked list

Given iterator variables Given iterator variables positionposition and and previousprevious, the following two lines of code , the following two lines of code will delete the node at location will delete the node at location positionposition::

previous.link = position.link;previous.link = position.link;

position = position.link;position = position.link;

Note: Note: previousprevious points to the node before points to the node before positionposition

15-40

Page 41: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Deleting a Node (Part 1 Deleting a Node (Part 1 of 2)of 2)

15-41

1. Existing list with the iterator positioned at “shoes”

"orange juice" "shoes" "socks " null"coat"

head previous position

2. Bypass the node at position from previous

previous.link = position.link;

"orange juice" "shoes" "socks" null"coat"

head previous position

Page 42: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Deleting a Node (Part 2 Deleting a Node (Part 2 of 2)of 2)

15-42

3. Update position to reference the next nodeposition = position.link;

"orange juice" "shoes" "socks" null"coat"

head previous position

Since no variable references the node "shoes" Java will automaticallyrecycle the memory allocated for it .

4. Same picture with deleted node not shown

"orange juice" "socks" null"coat"

head previous position

Page 43: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Adding and Deleting Adding and Deleting NodesNodes

Note that Java has Note that Java has automatic garbage collectionautomatic garbage collection In many other languages the programmer has to keep In many other languages the programmer has to keep

track of deleted nodes and explicitly return their track of deleted nodes and explicitly return their memory for recyclingmemory for recycling

This procedure is called This procedure is called explicit memory managementexplicit memory management The iterator variables The iterator variables positionposition and and previousprevious

can be used to add a node as wellcan be used to add a node as well previousprevious will point to the node before the insertion will point to the node before the insertion

point, and point, and positionposition will point to the node after the will point to the node after the insertion pointinsertion pointNode temp = new Node(newData,position);Node temp = new Node(newData,position);previous.link = temp;previous.link = temp;

15-43

Page 44: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Adding a Node between Adding a Node between Two Nodes (Part 1 of 2)Two Nodes (Part 1 of 2)

15-44

1. Existing list with the iterator positioned at “shoes”

"orange juice" "shoes" null"coat"

head previous position

2. Create new Node with "socks" linked to "shoes"

temp = new Node(newData, position); // newData is "socks"

"orange juice" "shoes" null"coat"

head previous position

"socks"temp

Page 45: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Adding a Node between Adding a Node between Two Nodes (Part 2 of 2)Two Nodes (Part 2 of 2)

15-45

3. Make previous link to the Node temp

previous.link = temp;

"orange juice" "shoes" null"coat"

head previous position

"socks"temp

4. Picture redrawn for clarity, but structurally identical to picture 3

"orange juice" "socks ""coat"

head previous temp

"shoes" null

position

Page 46: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Variations on a Linked Variations on a Linked ListList

An ordinary linked list allows movement in one direction An ordinary linked list allows movement in one direction onlyonly

However, a doubly linked list has one link that references However, a doubly linked list has one link that references the next node, and one that references the previous nodethe next node, and one that references the previous node

The node class for a doubly linked list can begin as follows:The node class for a doubly linked list can begin as follows:private class TwoWayNodeprivate class TwoWayNode{{ private String item;private String item; private TwoWayNode previous;private TwoWayNode previous; private TwoWayNode next;private TwoWayNode next; . . .. . .

In addition, the constructors and methods in the doubly In addition, the constructors and methods in the doubly linked list class would be modified to accommodate the linked list class would be modified to accommodate the extra linkextra link

15-46

Page 47: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

A Doubly Linked ListA Doubly Linked List

15-47

See LinkedList10.java

Page 48: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Adding a Node to the Adding a Node to the Front of a Doubly Linked Front of a Doubly Linked

ListList

15-48

Page 49: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Deleting a Node from a Deleting a Node from a Doubly Linked List (1 of Doubly Linked List (1 of

2)2)null

1. Existing list with an iterator referencing "shoes"

"coat"

head

"shoes” "socks” null

position

2. Bypass the "shoes" node from the next link of the previous node

position.previous.next = position.next;

null "coat"

head

"shoes” "socks” null

position

15-49

Page 50: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Deleting a Node from a Deleting a Node from a Doubly Linked List (2 of Doubly Linked List (2 of

2)2)3. Bypass the "shoes" node from the previous link of the next node

and move position off the deleted node

null "coat"

head

"shoes” "socks” null

position

position.next.previous = position.previous;position = position.next;

4. Picture redrawn for clarity with the "shoes" node removed since there are no longer references pointing to this node .

null "coat"

head

"socks”

position

15-50

Page 51: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Inserting a Node Into a Inserting a Node Into a Doubly Linked List (1 of Doubly Linked List (1 of

2)2)null

1. Existing list with an iterator referencing "shoes"

"coat"

head

"shoes” "socks” null

position

2. Create new TwoWayNode with previous linked to "coat" and next to "shoes"TwoWayNode temp = new TwoWayNode(newData, position.previous, position);// newData = "shirt"

null "coat"

head

"shoes” "socks” null

"shirt"

positiontemp

15-51

Page 52: Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Inserting a Node Into a Inserting a Node Into a Doubly Linked List (2 of Doubly Linked List (2 of

2)2)

15-52