Linked Lists in Action This chapter introduces linked lists. This presentation shows how to...

107
Linked Lists in Action This chapter introduces linked lists. This presentation shows how to implement the most common operations on linked lists. LINKED LISTS

Transcript of Linked Lists in Action This chapter introduces linked lists. This presentation shows how to...

Page 1: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked Lists in Action

This chapter introduces linked lists.

This presentation shows how to implement the most common operations on linked lists.

LINKED LISTS

Page 2: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Collection Classes - LINKED LIST The Java 2 platform contains a Collections API

This group of classes represent various data structures that store and manage objects

It includes classes such as ArrayList and LinkedListArrayList and LinkedList

22

Page 3: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Abstract Data Types – A Review

An abstract data type (ADT) is :

an organized collection of information containing

a set of operations used to manage that information

The set of operations includes methods such as add, delete , find etc..

The set of operations/methods define the interfaceinterface to to the ADTthe ADT

33

Page 4: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Abstract Data Types

A List ADT, for instance would define the operations that be used with the list, such as add, delete.

We have looked an array implementation of a list, now we will look at a Linked List.

44

Page 5: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Static vs. Dynamic Structures

A static data structure has a fixed size

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

55

Page 6: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

DRAWBACKS OF ARRAYS

The array implementation of our collection has one serious drawback:

you must know the maximum number of items in your collection when you create it.

66

Page 7: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked Lists

WHAT IF YOU DON’T KNOW THE NUMBER OF ITEMS BEFOREHAND?????

WHAT IF THE NUMBER OF ITEMS WILL VARY OVER TIME?

We need a dynamic data structure that grows and shrinks as necessary

77

Page 8: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Array Limitations Arrays

Simple, Fast

but Must specify size at construction time WHICH GIVES RISE TO “Murphy’s law”

Construct an array with space for n n = twice your estimate of largest collection

Tomorrow you’ll need n+1

88

Page 9: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked Lists - it is never fullit is never fullA linked list is a very flexible,

dynamic data structure:

no preset size required

items may be added to it or deleted from it at will.

No need to increase capacity when full -

it is never fullit is never full   

99

Page 10: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Object References

Recall that an object reference is a variable that stores the address of an object in memory.

A reference can also be called a pointer (to an object in memory)

and they are often depicted graphically:studentstudent

John Smith407253.57

1010

Page 11: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

References as Links

Object references can be used to create links between objects

Suppose a Person class contains a reference to another Person object

John Smith 40725

3.57 Person Jane

Jane Jones588213.72

1111

Page 12: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Self-Referential Objects

A Person object, for instance, could contain a reference variable to another Person object:

public class Person{ private String name; private String address;

private Person next; // a link to another Person object

// whatever else

}

1212

Page 13: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Intermediate Nodes

Problem:

Objects should not have to deal with the

details of the structure in which they are stored

E.g., the person class stored a link to the next person object in the list

1313

Page 14: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked Lists Instead, we can use a separate node class that :

holds a reference to the stored object and

a link to the next node in the list

This type of reference can be used to form a Linked List.

1414

Page 15: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

A Linked List of Persons

So by having a separate structure to contain the list of persons:

One object(object 1) is not dependent for its existence on another object (object 2)

And removing object2 would not require removing object1.

1515

Page 16: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Object References - ListNode class

Consider an object that contains a reference to another object of the same type:

class ListNode<T>class ListNode<T>

{{ T data;T data; // object stored in data– e.g. Client object// object stored in data– e.g. Client object

ListNode next; ListNode next; // reference to the next node // reference to the next node

}}

1616

data = Client

next = refers to next listnode

Page 17: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Two objects of this class can be instantiated and chained together.

The next reference of one Node object refers to the next node in the list.

The second objectsecond object’s’s next reference next reference refers to a third Node third Node object, and so on,

creating a linked list of Node objects.

1717

Client 1

next

Client2

next

Page 18: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

NODE S IN THE LIST

Each node will contain some data as specified by the programmer.

This constitutes a linked listlinked list

1818

Page 19: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked Nodes In a linked listlinked list, each item is allocated space as it is allocated space as it is

added to the list. (called dynamically)added to the list. (called dynamically)

A link (next) is kept within each item to the next Client in the list.

1919

Client 1

next

Client2

next

Page 20: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

 

Each node of the list has two elements :

1. the object being stored in the list, e.g. a client and

2. a reference to the next node in the list (nextnext)

The nextnext reference in the last node in the list contains a NULL pointer to indicate that it is the end or tend or tail of the list.

2020

Client 1

nextnext

Client2

next = null

Page 21: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked Lists As items are added to a list,

memory for a node is dynamically allocated. (Allocated as needed)

  Thus the number of items that may be added to a list

is limited only by the amount of memory available.

2121

Page 22: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

HEAD OF THE LIST The variable (or handle) which holds on to the list is

simply a pointer(reference) to the node at the

head of the list.

It is called headhead

Head Head holds the memory holds the memory address of the first nodeaddress of the first node

2222

Clientnext = null

Page 23: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked List -Flexible space use Dynamically allocate space for each element as

needed Includes a pointer to the next item

Linked list Each ListNode of the list contains

the data item (e.g. a Cliente.g. a Client)

nextnext - a reference to the next node

Data Next

object 2323

Page 24: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked Lists - WHAT IS HEAD?

Let’s implement a Collection structure – a linked list -

which has a reference to the first node calledHEAD

Head is initially NULL

Head = null

2424

Page 25: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked Lists The Linked List structure has a reference to the list: head which is initially NULL

TO Add first item to the head of the list Allocate memory for the ListNode Set its data reference to some object Set next to NULL Set head to reference the new node

Data Next

object

HeadListNode

2525

Page 26: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Add second item to the head of the list Allocate memory for the node - NewNodeNewNodeSet its data reference to some object (object2)Set new node .next to point to the node Head is pointing toSet Head to point to (reference) the new node

Data Next

object1

Head

FIRST node

Data Next

object2

NewNodeNewNode

2626

Page 27: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

2727

Linked Lists Add second item to the head of the list

Allocate memory for the node Set its data pointer to an object Set new node next to point to the node Head is pointing to Set Head to point to new node

Data Next

object1

Head

node

Data Next

object2

New node

Page 28: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Constructors of a ListNodeclass ListNode{amine the constructor for the class.

// This is one of This is one of the the constructors constructors in the ListNode clasin the ListNode classspublic ListNode(T initialData){ data = initialData; // data for the node next = null; // reference to next node}

where :

data - is the initial data of a new node e.g. a client , next - a reference to the next node in the list.

2828

Page 29: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

How to start the linked list Declare a head node to point to the first node in the

list . To create the first node

ListNode head = null; // initialize head

// now create the first node

head = new ListNode (“dan”);

Head now refers to a one-node linked list.

The data is “dan” and next is equal to null. See previous slide constructor

2929

Page 30: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

We will use We will use StringsStrings as as data .

data

next

dan

null

// Constructor ListNodepublic class ListNode{ private String data; private ListNode next; // constructors}Create the first Node:

head = new ListNode (“dan”);

Declarations for linked ListsDeclarations for linked Lists

Head

3030

ListNode

Page 31: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

data

next

nat

Declarations for linked Lists For this example, each node in the

linked list is an object of the class ListNode, as shown here with String data

next

null

public class ListNode{ private String data; private ListNode next; ...// Constructor sets next to null initally}

data

next

jay

datadan

Head

3131

Page 32: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Declarations for linked Lists

Each Each ListNode also contains a next reference which refers to the next ListNode in the list.

datajay

datanat

public class ListNode { private String data; private ListNode next; ... }

datadan

next

null

next

HeadHead

3232

Page 33: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

A program keeps track of the FIRST node by STORING ITS ADDRESS IN HEAD.

Head is a reference to a ListNode. Head is a reference to a ListNode. It holds the address of the first node. It holds the address of the first node.

Head and next both refer to list nodesHead and next both refer to list nodes They store the address of the next nodeThey store the address of the next node

data

next

dan

data

next

jay

datanat

null

head

5050

5050

next =52next =52

5252

next =60next =60

6060

50 is the address of the first node

50 is the address of the first node

50

Head

3333

52 is the address of the second node

52 is the address of the second node

Page 34: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

NEXT holds an address

In the previous slide, the head node holds the address of the first node which is 50

The second node’ next reference holds the address of the next node which is 52.

The third node’ next reference holds the address of the next node which is 60.

3434

Page 35: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Declarations for Linked Lists

We represent the empty list by storing

null in the head reference.

ListNode head = null;

headnull

3535

Page 36: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

The null reference

The null reference is a special JAVA constant.

It means the reference has no address

so it does not refer to anything.

3636

Page 37: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Null referencesNull references

Null references are used in several instances.

When a object is declared but not instantiated. Client client;

Client is initially null

For the next part next part of the final node in a linked list.

When we have an empty list, the head and tail reference variables are null.

3737

Page 38: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Null Pointer Exceptions

When a reference variable is null,

you cannot call any of the methods associated with variables’s class. E.g.;

ListNode head = null; // head is a null referemce

head.next; // error - no next reference yet exists.

The second line will result in a NullPointerException.

3838

Page 39: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Inserting Nodes at the front of the list. To add to front of list,

we create a reference to the head node and call it head.

Remember head is initially null.

The code to create the head node is:

ListNode head = null;

3939

Page 40: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

4040

We could use this code if the list is initially empty:ListNode head = null;ListNode head = null;

// create the node -- uses constructorcreate the node -- uses constructorListNode newnode = new ListNode(data1, ListNode newnode = new ListNode(data1, null);null);head = newnode;head = newnode; //Point head to it //Point head to it

ORBelow is a shorter version of the previous two lines:

ListNode head = new ListNode(data1, null)ListNode head = new ListNode(data1, null)

Inserting an Node at the Front

head data1

null

Page 41: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

This is a constructor IN THE Linkedlist class:

public ListNode ( T data, ListNode nxt){ data = initialData; next = nxt;}

INSERTING A NODE

head = new ListNode(data1, head = new ListNode(data1, null);null);

//Where head is initially null

head = new ListNode(data1, head = new ListNode(data1, null);null);

//Where head is initially null

Does the constructor workcorrectly for the

first node on a new

list ?

4141

Page 42: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Creating the first node in a list - Review

head = new ListNode( data1, null)

creates a new node with data1 as the data and null is stored in next.next.

Head now holds the address of the node with data1 :

4242

Head = 50

data1

null

5050

Page 43: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Inserting an Node at the Front Create a new node…red boxes

are addresses of nodes.

Head holds the address of the first node - 50

data1

nullheadhead

A new nodeA new node

5050

50

4343

Let’s add another node to the front of the listLet’s add another node to the front of the list

Page 44: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Inserting an Node at the Front

We want to add a new entry, data2, to the front of the linked list shown here.

null

head data1

New node

50

4444

50

Page 45: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Inserting an Node at the Front Create a new node... Place the data in the new

node's data field – this is data2.

Next = nullhead

data1

data2

5050

Create the new node:

ListNode newnode = new ListNode( data2, ListNode newnode = new ListNode( data2, null)null)

Create the new node:

ListNode newnode = new ListNode( data2, ListNode newnode = new ListNode( data2, null)null)

4545

50

newnodenewnode

null

Page 46: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Inserting an Node at the Front of the list, reassign head Inserting an Node at the Front of the list, reassign head to itto it

null

head

data2

data1

next = 50next = 50

5050

Connect the next (50) reference of newnode to the node head is currently pointing to.

So now So now headhead and and newnode.nextnewnode.next point to the same nodepoint to the same node

newnode

4646

ListNode newnode = new ListNode( data2, null)ListNode newnode = new ListNode( data2, null)

newnode.next = headnewnode.next = head

newnode.next refers to the same node as head

newnode.nextnewnode.next

Page 47: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Inserting an Node at the Front

null

head

ListNode newnode = new Listnode(data2, null) newnode.next = head; head = newnode ; // we store address 84 in head

data2 is now the new first node of the linked list – its address is 84

data1data284

NEXT = 50

84

4747

50Finally, we point head to the newnode head = newnode;head = newnode;Head holds address of Head holds address of the newnode - 84the newnode - 84

Newnode’s Newnode’s address is 84address is 84

Page 48: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

4848

The brute force way to insert the node at the head of the list would The brute force way to insert the node at the head of the list would be:be:

public void insertFirst(T data){// create a nodeListNode newnode = new ListNode(data, null);

if(isEmpty()) // is the list is empty head = newnode; // point head to the new node

else // list is not empty

{ // set the next pointer of newnode to what head is pointing to newnode.next = head ; head = newnode // point head to newnode }}

Page 49: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

CHALLENGECHALLENGE

For homework, extra credit pts on your quiz if you can do the insertion code in the previous slide in one line of code.

You may assume that head has been set to null.

4949

Page 50: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Adding to a list

This strategy is fast and efficient, but each item is added to the head of the list.

An alternative is a list which contains both head and tail pointers:

The code for Add is modified to make a list in which new nodes are added to the list at the end.

5050

Page 51: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Caution! Always make sure Always make sure

that your linked list that your linked list methods work methods work correctly with an correctly with an empty listempty list.

EMPTY LIST

Page 52: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked Lists Add time

Constant - independent of n – no loops Search time

Worst case - n

Data Next

object

Head

Collection

nodeData Next

object2

node

5252

Page 53: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Pseudocode for Inserting ListNodes

Nodes are often inserted at places other than the front of a linked list.

There is a general pseudocode that you can follow for any insertion function. . .

First determine if the node is the first node , if so, call method insertFirst(data)

5353

Page 54: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Otherwise (if the new node will not be first):

then a reference named current must be placed on the list

This special node is called the selected node and the new node is inserted right after the selected node.

Pseudocode for Inserting NodesPseudocode for Inserting Nodes

5454

Page 55: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Pseudocode for Inserting ListNodes

dan

jay

nat

nullhead

Otherwise (if the new node will not be first): Start by setting a reference named current to refer to the

node before the new node.

THE NEW NODE WILL BEINSERTED AFTER THE NODE CURRENT IS POINTING TO

THE NEW NODE WILL BEINSERTED AFTER THE NODE CURRENT IS POINTING TO

current

next

5555

Page 56: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Pseudocode for Inserting ListNodes

What is the name of this link?

dan

jay

nat

nullhead

Otherwise (if the new node will not be first):

Start by setting a reference named current to refer to the node just before the new node's position.

Look at the linkwhich is in the node

previous

Look at the linkwhich is in the node

previous

Look at the link(next) which Look at the link(next) which is is in the nodein the node current iscurrent ispointing topointing to

Look at the link(next) which Look at the link(next) which is is in the nodein the node current iscurrent ispointing topointing to

next

5656

current

Page 57: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Pseudocode for Inserting ListNodes

What is the name of this link ?

dan

jay

nat

nullhead

Otherwise (if the new node will not be first): Start by setting a reference named current to refer

to the node which is just before the new node's position

current

next

5757

This link is called current.next Or current.getNext()

This link is called current.next Or current.getNext()

Page 58: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Pseudocode for Inserting Nodes

dan

jay

nullhead

Otherwise (if the new node will not be first):Otherwise (if the new node will not be first):

Start by setting a reference named current to refer to the node which is just before the new node's position

Current refers to the headof a small linked

list, with jay and nat

Current refers to the headof a small linked

list, with jay and nat

current

next

5858

nat

Page 59: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Pseudocode for Inserting ListNodes

dan

10

nat

nullhead

Otherwise (if the new node will not be first):

Let’s insert a new nodeafter the node containing dan

Let’s insert a new nodeafter the node containing dan

jay

currentcurrent

current

next

5959

next

next

Page 60: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

These are the contructors for the Listnodepublic ListNode() // NO PARAMETERS// NO PARAMETERS

{{

data = null; // data for the node

next = null; // reference to next node

}

///************************************************************

public ListNode(T initialData) // with THE DATA PARAMETE// with THE DATA PARAMETERR

{

data = initialData; // data for the node

next = null; // reference to next node

}

///************************************************************

public ListNode(T initialData, Listnode nextnode) // both paramters{

data = initialData; // data for the node

next = nextNode; // reference to next node

}

6060

Page 61: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

6161

InsertAfterInsertAfter Let create the new node and put Fred in it

dannat

sam

head

jaycurrent

NEWNODE

ListNode newnode = new ListNode(); newnode.data = “Fred”;newnode.data = “Fred”; newnode.next = current.next;newnode.next = current.next; current.next = newnode;current.next = newnode;

fred

next

next

null

6161

next

next

Page 62: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

InsertAfter

public void insertAfter(T newData){ // where newData = “Fred” ListNode newnode = new ListNode(); newnode.data = newData;

// Now we have to attach newnode.next to the list newnode.next = current.next; current.next = newnode;}

We use constructor with one parameter

6262

Page 63: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Then : Store the address in current.next into

newnode.next so they both refer to ‘jay’

dannat

sam

head

jaycurrent

NEWNODE

pvoid insertAfter(String newData){ ListNode newnode = new ListNode();ListNode newnode = new ListNode(); newnode.data = newData;newnode.data = newData; newnode.next = current.next;newnode.next = current.next; current.next = newnode;current.next = newnode;}}

fred

nextnext

next

null

6363

next

next

Page 64: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

6464

dannat

sam

head

jaycurrent

NEWNODE

pvoid insertAfter(String newData){ ListNode newnode = new ListNode();ListNode newnode = new ListNode(); newnode.data = newData;newnode.data = newData; newnode.next = current.next;newnode.next = current.next; current.next = newnode;}

fred

nextnext

next

null

6464

next

next

Now, point current.next to newnodeNow, point current.next to newnode

Page 65: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Reduce number of lines

6565

public void insertAfter(String newData) { ListNode newnode = new

ListNode(); newnode.data = newData; newnode.next = current.next; current.next = newnode; }

Can we reduce the first three lines of code in this method to one line?

Page 66: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

InsertAfterInsertAfter Then : Reduce the first three lines to one line

dannat

sam

head

jay

current

current

public void insertAfter(String newData){ // first three lines in one line ListNode newnode = new ListNode(newData, current.next)ListNode newnode = new ListNode(newData, current.next) current.next = newnode;}

20

next

next

fred

head

6666

next

null

next

NEWNODE

Page 67: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

6767

InsertAfter - a shorter versionInsertAfter - a shorter version Then : Set the current.next to refer to the new node

dannat

samhead

jay

current

current

// Let’s compact the code all to one line:public void insertAfter(String newData){

ListNode newnode = new ListNode(newData, current.next)ListNode newnode = new ListNode(newData, current.next) current.next = newnode;}

fred

next

next

head

6767

next

null

next

NEWNODE

Page 68: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Pseudocode for Removing ListNodes

Nodes often need to be removed from a linked list.

As with insertion, we can

remove a node from the front of a list,

remove a node from elsewhere.

We’ll look at the technique for removing a node from the front of a linked list.

6868

Page 69: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Removing the Head Node

fred nat sam

null

headdan

head = head.next;Draw the change that this statement will make to the linked list.

next

6969

next next

Page 70: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Removing the Head Node

fred nat sam

nullhead

dan

head = head.next;This points head to node after the first Node

next

7070

next next

Page 71: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Removing the Head Node

head = head.next; orhead = head.getNext();// if node class is separateNow the node is deleted from the head of the list.

fred nat sam

nullhead

dan

7171

Page 72: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Summary

It is easy to insert or remove a node at the front of a list.

You also need a technique for inserting or removing a node elsewhere.

We will now provide an implementation that will

delete at the head node and also

elsewhere on the list.

7272

Page 73: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Deleting a node not at the head

Deleting a node not at the head is similar to adding a node to the middle of the list.

current will point to the node to be deleted.

WE also need another reference to the node that is just before current.

This reference is called previous :

7373

Page 74: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Deleting from the middle calls find(target) method Deleting from the middle calls find(target) method firstfirst

fred jay sam

nullhead

dan

deleteNode()

Previous refers to the node before the one to be deleted - Current refers to node to be deleted

previous

This arrow is previous.next

This arrow is current.next

current

7474

next next

Page 75: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Deleting a Node

The method remove{T data} requires that current refer to the node to be deleted.

Remove calls Find(T data) which assigns current to refer to the node to be deleted.

It also places previous on the node behind current

7575

Page 76: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Deleting Anywhere on the List

We call the method witWe call the method with: h: Remove(T data)

fred nat sam

null

This arrow is previous. nextThis arrow is previous. next This arrow is current.nextcurrent.nextThis arrow is current.nextcurrent.next

previous current

7676

head

dan

next next

previous.nextprevious.next points to the points to the node current node current refers to. current.nextrefers to. current.next points to the node after points to the node after the node to be deleted (“sam”).the node to be deleted (“sam”).

Page 77: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Deleting from the middle

fred nat sam

nullhead

dan

The next portion of previous now points(refers) to the node after current. We must also advance current to the next nodeprevious current.

previous.next = current.next; current = current.next;

next

7777

nextnext

Page 78: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Deleting anywhere on the list 1) previous.next now contains the

address of the node (Sam) . 2) Current 2) Current is advanced to refer to the

node which contains “Sam”

NOW previous.next and current previous.next and current refer to same node refer to same node

fred

nat

sam

null

previous current.

previous.next = current.next; current = current.next;

previous.next = current.next; current = current.next;

7878

nextnext

Page 79: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Removing a node -The Find method puts previous and current on the list

where the node is to be deleted

public void remove(T data) { // remove first calls the find method find(data);

if(current != null && previous != null){ previous.next = current.next; current = current.next;} }

7979

Page 80: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Remove()

The remove(T data) method works even if the node is a tail node.

In this case, the next of the previous node will be assigned the null value.

8080

Page 81: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Deleting from the list at the tailDeleting from the list at the tail

fred nat sam

null

head

dan

The next portion of previous now points to what current.next points, and current points to null. previous current

previous.next = current.next; current = current.next;

null

8181

next

Page 82: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Pseudo-code for Removing a nodepublic void remove() {

// if current and previous are not null

// point previous.next to what current.next is pointing to

// Point current to what current.next is pointing to

// else if at the head node – point head to what

//current.next is pointing to and set current// equal to headAlways check for the Empty List FIRSTAlways check for the Empty List FIRST

}}

8282

Page 83: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Traversing a Linked List

To traverse a linked list, we must first assign a next variable - such as cur - to some node.

To traverse the list, we move cur to the next node by using the code:

cur = cur.next // advance cur to the next node

This assignment says “move cur to point to what cur.next points to” - which

advances cur to next node. Or we can use:

cur = cur.getNext{} // uses getter method for ‘next’8383

Page 84: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Searching a linked list To find a particular node in a list,

we create a method that returns the node that contains the element. The method:

public ListNode Find(T target) { }

searches for a node containing the target (the data)

It returns a reference to the first node that contains the target data.

To call the method , use:

ListNode node = ListNode node = Find(target)Find(target)8484

Page 85: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

onList()

Because Find( target) returns a ListNode, we need to write another method that will return a boolean.

Our application class should not have to deal with ListNodes.

Our methods should be implementation independent.

The user does not have to know if we used an ArrayList of Linked List

So returning a boolean can be done in any class8585

Page 86: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

The Find (target ) method returns a ListNode

public ListNode find (target)

This is necessary for some methods that use it.

However, outside classes will not know what a Listnode is. SO

We write another Find method for the outside classes that returns a boolean

public boolean find (target)

public boolean find(T target)8686

Page 87: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Searching / traversing a list.public boolean Find(T target)

{

// this is how you traverse a linked list

boolean found = false;

ListNode curr; // declare variable to traverse the list

for(curr = head; curr!= null; curr= curr.getNext()) {

// put in code to find target and return true if found

} // close loop

return found ;

}// close method

8787

Page 88: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Doubly Linked Lists

Doubly linked lists have a pointer to the preceding item as well as one to the next.

They permit scanning or searching of the list in both directions.

(To go backwards in a simple list, it is necessary to go back to the start and scan forwards.)

Many applications require searching backwards and forwards through sections of a list:

8888

Page 89: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked Lists - Doubly linked

Doubly linked lists Can be scanned in both directions

public ListNode(T initialData,) { data = initialData; Listnode previous, next; }

head

tail

prev prev prev

8989

nextnext

Page 90: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Doubly Linked Lists In this case, the node structure is altered to have two

links:

class ListNode

{

T data;

ListNode previous, next; // link to node before

} // and after

9090

Page 91: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Circularly Linked Lists

By ensuring that the tail of the list is always pointing to the head,

we can build a circularly linked list.

A circularly linked list would more likely be used in an application which required "round-robin" scheduling or processing.

9191

Page 92: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Analysis of Linked Operations Since the order is irrelevant, and

there is no capacity to expand

adding an element to the List is O(1)

Removing a particular element, because it must be found, is O(n)

Removing any item, any item, can be done at the head or tail and thus is O(1);

9292

Page 93: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Linked List The linked list implementation has exchanged

flexibility for efficiency –

On some systems, the need to allocate memory can be relatively expensive.

Pre-allocation in the array-based implementation is generally more efficient.

BUT, there are circumstances where Linked List is needed.

9393

Page 94: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

LINKED LIST VS ARRAY

However, there are many situations where a linked list is more efficient e.g.

Applications that are unsorted - WHY?

Applications where the size is relatively small . WHY?

More examples of such trade-offs will be found later.

9494

Page 95: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Free Memory Memory is just an array of data.

Each entry has an address and a value

After a series of memory allocations and

de-allocations, there are blocks of free memory

scattered throughout the available heap space.

9595

Page 96: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Memory allocation

In order to be able to re-use this memory,

memory allocators will link freed blocks together in a free memory list

The computer keeps references to blocks of free memory

9696

Page 97: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Free Memory An external pointer(head) points to the

first block in the free list.

When a new block of memory is requested,

the allocator scans the free list looking for a suitable block

It will delete the block from the free list

(re-linking the free list around the deleted block).

9797

Page 98: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Free Memory

Many variations of memory allocators have been proposed:

Refer to a text on operating systems or implementation of functional languages for more details.

The entry in the index under garbage collection will address it.

9898

Page 99: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

An abstract data type defines a type of structure that stores data ( e.g. an array)

It stores the data in a class along with the operations that can be performed on that data

e.g. An ArrayList, A LinkedList, a Stack, A Graph etc.

Abstract Data Types

9999

Page 100: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Abstract Data TYPE

The Abstract Data Type lists a set of abstract methods

Each class that implements the ADT must implement all these methods.

E.g. in the List interface has methods like:

add, delete etc.

100100

Page 101: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Cohesion

Well- designed ADT’s have strong Well- designed ADT’s have strong relationships between the relationships between the parts of a parts of a class class so so

CohesionCohesion is a goal that you should is a goal that you should seek in designing your ADT’sseek in designing your ADT’s

101101

Page 102: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Well-designed ADT’s have little or no Well-designed ADT’s have little or no couplingcoupling To create our Abstract Data Type we need

to be sure that the methods are cohesive.

Coupling measures the strength of the relationship between two components.

It represents the glue that holds two separate components together.

This should be minimal in an object-oriented program

102102

Page 103: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Coupling and Cohesion

We want to minimize the degree of coupling between any two classes of our system

so they can operate as independently independently as possibleas possible. .

Thus any changes we make will only effect a small portion of the program.

ALL the methods for the Linked List should be in the Linked List class.

103103

Page 104: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

CLASS INDEPENDENCE FROM OTHER CLASsES

This makes errors easier to track

and less likely to affect

another part of our system.

104104

Page 105: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Coupling and Cohesion

We want to maximize the cohesion in a class

Cohesion means that the more tightly related the parts of an item are

the more logical its operations are.

Coupling means that an object depends on another class for some of its operations or data

This creates systems that are very difficult to debug

105105

Page 106: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

ADT’s

Cohesion is the strength of the relationships among the parts of one component

so that the parts of the component can be thought of as one piece.

E.g. in a Client class, we would have a firstname and lastname etc. but not have a reference to another client defined inside it.

106106

Page 107: Linked Lists in Action  This chapter introduces linked lists.  This presentation shows how to implement the most common operations on linked lists. LINKED.

Objectives

Your goals are:

1.a method should only accomplish one logical

function

2. an object should represent a single concept or entity. A Student , A Client

An ADT by its definition minimizes the coupling between objects.

107107