Understanding Linked Lists

1028 Words3 Pages

Understanding Linked Lists

Introduction:

Arrays in Java can be tedious to work with because they require a set amount of memory to be allocated on creation and they do not allow for easy removal or insertion of elements. A linked list is a simple solution to the shortcomings of arrays. In this assignment, you will be creating the LinkedSimpleCollection and the LinkedSimpleIterator classes which implement the SimpleCollection and SimpleIterator interfaces, respectively. By completing this assignment, you will learn how a linked collection works and about its benefits and shortcomings.

Part 1: Nodes

In order to build the LinkedSimpleCollection class, you will first need to create the Node class. Each Node contains an element and a pointer to another Node. Nodes, when combined, form the structure of a linked list. The element of a Node can be of any type, so the Node class must be generic. The Node class has no methods, but the constructor of the Node class should take two arguments: the element of a generic type and a pointer to another Node which we will call next. By creating Nodes with a pointer to another Node, you are setting up the basis for a LinkedSimpleCollection.

You can test the Node class with the following DrJava interactions:

> Node n1 = new Node(“Foo”,null)

> n1.element

“Foo”

> n1.next

null

> Node n2 = new Node(“Bar”,n1)

> n2.element

“Bar”

> n2.next.element

“Foo”

Part 2: Creating a Linked List

Keeping track of manually linked Nodes can be difficult, so we need a class that will link these Nodes automatically. In this part of the assignment you will create the LinkedSimpleCollection class. This class has a constructor and must satisfy its contract to the SimpleCollec...

... middle of paper ...

... the LinkedSimpleCollection class. This can be done by creating a new LinkedSimpleIterator in the iterator method of LinkedSimpleCollection and passing this to the constructor.

You can test the LinkedSimpleIterator class with the following DrJava interactions:

> LinkedSimpleCollection c = new LinkedSimpleCollection ()

> c.add(“Four”)

True

> c.add(“Three”)

True

> c.add(“Two”)

True

> c.add(“One”)

True

> SimpleIterator Iterc= c.iterator()

> Iterc.hasNext()

True

> Iterc.next()

“One”

> Iterc.next()

“Two”

> Iterc.hasNext()

True

> Iterc.remove()

> Iterc.next()

“Four”

> Iterc.hasNext()

False

You can now step through a linked list, but notice that after stepping through the list it is impossible to move backwards without creating a new iterator of the same list. This flaw is one of the shortcomings of one-way linked lists.

Open Document