Linked List Data Structure with JAVA iterator

Introduction

Linked list is a data structure where nodes are kept in sequence as in a graph but in a linear manner.
As in the above graph what we all keep is a pointer/reference to the head of the list. This data structure can be used to Implement a Stack or a Queue very easily. Because we always have a pointer to the end and the start of the chain. We may also access other elements but it'd need us to iterate thus giving O(n) time complexity.

JAVA Iterator/ Iterable Interface

JAVA provides us with a nice interface which is the Iterator interface which let us use foreach or enhanced for loops. This is very important if we are to use Lamda expressions which is a handy feature in JAVA 8 release. You may be familiar with these if you are already an expert in python programming, where we use these Lamda expressions frequently to make clean code.

Once Iterator interface is implemented methods hasNext() and next() should be implemented giving us the ability to use aforementioned looping. This will be more clear with the code. I have included the codes of two JAVA files LinkedList.java and LLMain.java. We should make sure that we keep track of the current location of the pointer to support iterator. Also I have used a variable to keep if the looping has started. This is just for the implementation of the iterator. What is important is the concept.

The Itarable interface is enables us to create an object iterable. Which means and Iterator object can be obtained. This is if we use the Iterator design pattern. Which is apparently not necessary for our job.

JAVA Code

Make sure you don't import the JAVA LinkedList class :) Then no point!


Feel free to visit the original repository of algorithms at:
URL https://github.com/anuradhawick/Algorithms

Comments

Popular Posts