Top Banner
8/13/2019 100_lecture26.pdf http://slidepdf.com/reader/full/100lecture26pdf 1/20 Introduction to Computation and Problem Solving Prof. Steven R. Lerman and Dr. V. Judson Harward Class 26: Class 26: Linked Lists Linked Lists 2 The Java Collection Classes The java.util package contains implementations of many data structures that we are also going to discuss and implement in a simpler way in class. You are welcome to use the standard Java implementations in problem sets. They are more elaborate and abstract than the implementations we will develop. Learning how to implement a few data structures makes you more sophisticated in how you use all data structures. We will cover the Java implementations in a later lecture.
20

100_lecture26.pdf

Jun 04, 2018

Download

Documents

Mayank Mehta
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 1/20

Introduction to Computation and Problem

Solving

Prof. Steven R. Lerman

and

Dr. V. Judson Harward

Class 26:Class 26:

Linked ListsLinked Lists

2

The Java Collection Classes

• The java.util package containsimplementations of many data structures that weare also going to discuss and implement in asimpler way in class.

• You are welcome to use the standard Javaimplementations in problem sets. They are moreelaborate and abstract than the implementationswe will develop.

• Learning how to implement a few data structuresmakes you more sophist icated in how you use alldata structures.

• We will cover the Java implementations in a later lecture.

Page 2: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 2/20

3

Goals

data structure (a Linked List) using linking

rather than arrays.

data structure is as much as its interface

(set of methods).

We will examine and build a new kind of

The most important theme, however, is

that implementation affects how useful a

4

 A list is a collection of elements that has a

 –

 –

 –

order an element at a time.

Lists as an Abst ract Data Type

particular order.

It can have arbitrary length.

You should be able to insert or delete an

element anywhere.

You should be able to go through the list in

Page 3: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 3/20

5

 A List Interface

 public interface List<E> {

 public boolean isEmpty();

 public void addFirst( E e );

 public void addLast( E e );

 public boolean contains( E e );

 public boolean remove( E e );

 public E removeFirst()

throws NoSuchElementException;

 public void clear();

 public int size();

}

6

• There are certain obvious things we wouldlike to do with lists that we can't do using

 –

 –

end?

• One approach is to number or index thepositions in the list.

Lists and Ordinal Position

only this interface. Two examples:How would you access the elements of the lis tif you did not know them in advance?

How would you insert an item into the list atany other position than the beginning and the

Page 4: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 4/20

Page 5: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 5/20

9

Iterators

•  An iterator is a helper class designed tobe used with a List or other collection

class. Think of it as a movable bookmark.

• It has methods to return the collection's

members one at a time.

allow the collection to be modified relative

to the current position of the iterator.

Iterators can also implement methods that

10

SListIterator Interface

 public interface SListIterator<E>

{

 public boolean hasNext();

 public E next()

throws NoSuchElementException;

 public void remove()

throws IllegalStateException; public void add( E e );

 public void set( E e )

throws IllegalStateException

}

Page 6: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 6/20

11

Iterator

•next().

ListIterator

• next()

• remove()

• add()

next() add(), the inserted

• next()

Methods

The type of iterator we present here returns a new elementand advances to the next w ith the same operation,There is no way to go back using this in terface. The Java

allows you to go forwards and backwards.

The most recent element returned by is the currentelement.

will delete the current element from theunderlying collection. set() will change it.

will insert a new element after the current elementand before the element that would be returned by thefollowing call to . After a call toelement becomes the new current. A call to next() will

return the element after the inserted one.The first call to returns the first element of the list.Before the first call to next(), there is no current element.

12

Iterator and its Underlying List

•  An i terator is an object based on an

create an iterator for a collection.

•List interface:

•List?

underlying collection so we need a way to

We do this by adding a method to our

 public SListIterator slistIterator();

Can you have 2 iterators over the same

Page 7: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 7/20

13

. . .

. . .

while ( iter.hasNext() )

{

String s = iter.next();

. . .

}

Using an Iterator

List<String> myList = new SLinkedList<String>();

SListIterator<String> iter = myList.slistIterator();

14

 An SListIterator in Action

green

red

purple

orange

Iterator

current

undefined green

red

purple

orange

st

next()

current is

green

green

red

purple

orange

black

black

green

red

purple

orange

nd

next()

black

current is

black

current is

red

New  Aft er 1 cal l to

 Aft er add ing Aft er 2 cal l to

Page 8: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 8/20

15

 An SListIterator in Act ion, 2

green

black

purple

orange

current is

undefined

green

black

purple

orange

rd

next() current is

purple

 Aft er cal li ngremove()

 After 3 cal l to

16

List Implementation Stategies

• Arraylist

except the end of the list is very expensive

insertion until the end must be moved back

• linkedimplementation (e.g., Java’s LinkedList)

There are many ways to implement a list.

In array-based implementations like the Javainserting an element at any place

because all the elements from the point of

to make room for the new entry. There is asimilar problem with deletion.

For this reason, lists frequently use a

Page 9: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 9/20

17

Singly Linked Lists

link

next.

Linked lists are like freight t rains.

Each item to be put on the list is contained in an

instance of a new type of object called the

corresponding to a freight car.

In a singly linked list, the link not only contains

the listed item, but it also points to the next item

in the list as one freight car is coupled to the

The last link in the list points to nothing.

18

Singly Linked List Diagram

List

first last

Link 1

Item 1

Link n

Item 2 Item n

... nullLink 2

Page 10: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 10/20

19

Singly Linked Lists, 2•

easier to append i tems.

• andthe list ins tance “points” or “ . In

reference.

•points to the next element.

The list object itself points to the link holding thefirst l isted item, and often holds an additionalreference to the last link of the list to make it

We say that a link “ contains” or “ points to” ,holds a pointer”

Java these are all synonyms for holding a

So the link doesn't really contain the item. It

simply holds a reference to the listed item.The last link holds a null reference in the field that

20

List: List interface

SListIterator: List iterator interface

SLinkedList: List implementation

SLinkedListApp:

SLinkedListView:

IteratorView: List iterator GUI

 A Singly L inked List Demonstration

main() application

List GUI

Page 11: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 11/20

21

The Link Inner Class public class SLinkedList<E> implements List<E> {

 private static class SLink<E>

{

E item;

SLink<E> next;

SLink( E e, SLink<E> n )

{ item = e; next = n; }

SLink( E e )

{ this( e, null ); }

}

. . .

22

The SLinkedList Data Members

• first

• last and length

them up to date makes the calls size() and

append() much faster.

 private int length = 0;

 private SLink<E> first = null;

 private SLink<E> last = null;

Only is necessary.

could be found by traversing

the list, but having these members and keeping

Page 12: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 12/20

23

Object equals method

• contains( E e ) and remove( E e ) E e

it?

• ==)?

that is

{

}

== vs the

must search forin the list. What does it means to find

Must the list contain a reference to the identical object (Or is it suff icient that the list contain a reference to an object

equal but possibly distinct?

static private <E> boolean

objectEquals( E a, E b )

if ( a == null )

return ( b == null );

else

return a.equals( b );

24

Beware the Special Case

 –

 –

 –

 –

The tricky part about implementing a linked list isnot implementing the normal case for each of themethods, for instance, removing an object fromthe middle of the list .

What's tricky is making sure that your methodswill work in the exceptional and boundary cases.

For each method, you should think through

whether the implementation will work onan empty list,

a list with only one or two elements,

on the first element of a list,

on the last element of a lis t.

Page 13: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 13/20

Page 14: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 14/20

27

addFirst(), special case

List

first last

Link 1

Item 1

null

List

first last

null

before after

28

{

{

}

{

}

}

addFirst(Object o)

 public void addFirst(E e)

if ( first == null ) // if the list is empty

first = last = new SLink<E>( e );

else

first = new SLink<E>( e, first );

length++;

Page 15: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 15/20

29

removeFirst(), before

List

first last

Link 1

Item 1

Link n

Item 2 Item n

... nullLink 2

30

removeFirst(), after

List

first last

Link 1

Item 1

Link n

Item 2 Item n

... nullLink 2

Page 16: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 16/20

31

removeFirst(), special case

List

first last

Link 1

Item 1

null

List

first last

Link 1

Item 1

null

before after

32

removeFirst()

{

}

}

 public E removeFirst()

throws NoSuchElementException

if ( first == null ) // if list is empty

throw new NoSuchElementException();

else {

SLink<E> t = first;

first = first.next;

// if list had 1 element and is now empty

if ( first == null ) last = null;

length--;

return t.item;

Page 17: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 17/20

33

SListIterator as Inner Class

 public class SLinkedList<E> {

. . .

 public SListIterator<E> slistIterator()

{return new SLinkedListIterator();

}

 public class SLinkedListIterator

implements SListIterator<E>

{

. . .

}

}

34

contains()

while ( iter.hasNext() ) {

if ( objectEquals( iter.next(), e )) {

return true;

}

}

return false;}

 public boolean contains(E e) {

SListIterator<E> iter = new SLinkedListIterator();

Page 18: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 18/20

35

• Since our ListaddLast() and removeFirst() methodsyou can implement a trivialof the SLinkedList

• How would the implementation bechanged if each link had a back reference(previous) as well as a forward reference

it) doubly linked lists. What operationsbecome easier?

Linked List Uses and Variations

interface possesses

queue on topconcrete data type.

(next)? Such lists are called (you guessed

36

Linked Lists vs. Array Lists

lists.

linked lists.•

Lists that are relatively static (few additions or

deletions) are frequently more efficient as array

Lists accessed through ordinal position are

usually implemented as array lists .

Highly dynamic l ists are often more efficient as

The time for many basic operations on a linked

list (adding an element, removing an element) are

fixed, but can vary widely for array lists .

Page 19: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 19/20

37

Iterator Caution

removeFirst()

next()

should happen?

Let's carry out a thought experiment. You create and populate

a list. You create an iterator over that list. You callon the list to delete the first element of the

list. Now call on the iterator. What happens? What

 Although our implementation is reasonably robust, it erators

assume that they are called over a fi xed list. That is, they do

NOT guarantee correct results if you modify the list after

iterator construction using either list or another iterator

instances methods. How might you " fix" this? What does

fixing mean? Would it be better to have an iterator thatalways gave "correct" results or an iterator that threw an

exception if the underlying li st had been modified?

38

LinkedList, Exercise

• Lecture26.zip from

•Lecture26 files. Compile and run.SLinkedListApp contains main().

•implementation in SLinkedList and List. The

• The addLast and remove

implementations have been removed.

Download the Java files inthe class web si te and save them to a newdirectory.

Create a new Eclipse project based on the

Play with the simulation. Look at the

rest of the files manage the simulation. You don'tneed to look at them unless you are curious.buttons don't work

because the corresponding method

Page 20: 100_lecture26.pdf

8/13/2019 100_lecture26.pdf

http://slidepdf.com/reader/full/100lecture26pdf 20/20

39

LinkedList , Exercise, 2

• addFirst()addLast()  (

••

remove()

•ListUtil:

 public static void doubleList(

SLinkedList<integer> l )

• doubleList()

for Integer

• Compile and test.

Look at the method, and then write. Beware of special cases what are they?).

Compile and test using the simulation.Now look at the contains() method, and then write

. Compi le and test.

The main Li st view also has a new red button labelled"double" . Click it. It doesn't do anything. Yet.

Clicking the double but ton calls a method in a new class

is almost empty. Write an implementation

doubleList() that uses an iterator for the list, l, anddoubles each on the list.