blog




  • Essay / Understanding Linked Lists - 1028

    Understanding Linked ListsIntroduction:Arrays in Java can be tedious to use because they require allocating a set amount of memory during creation and they do not allow deleting or to easily insert elements. A linked list is a simple solution to the shortcomings of arrays. In this assignment, you will create the LinkedSimpleCollection and LinkedSimpleIterator classes which implement the SimpleCollection and SimpleIterator interfaces, respectively. By completing this assignment, you will learn how a linked collection works and its advantages and disadvantages.Part 1: NodesTo create the LinkedSimpleCollection class, you will first need to create the Node class. Each node contains an element and a pointer to another node. The 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 must take two arguments: the element of a generic type and a pointer to another Node that we will call next. By creating nodes with a pointer to another node, you establish the basis of a LinkedSimpleCollection. You can test the Node class with the following DrJava interactions:> Node n1 = new Node("Foo",null)> n1.element" Foo"> n1.nextnull> Node n2 = new Node("Bar",n1)> n2.element"Bar" > n2.next.element"Foo"Part 2: Creating a linked listKeeping track of manually linked nodes can be difficult, so we need a class that will automatically link these nodes. In this part of the assignment, you will create the LinkedSimpleCollection class. This class has a constructor and must satisfy its contract with SimpleCollec...... middle of paper ...... the LinkedSimpleCollection class. This can be done by creating a new LinkedSimpleIterator in the iterator method of LinkedSimpleCollection and passing it 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()FalseYou can now iterc.hasNext()FalseYou can now iterate through a linked list, but note that after iterating through the list it is impossible to go back without creating a new iterator of the same list. This flaw is one of the flaws of one-way linked lists.