Implement iterator in Doubly-Linked List - java

How do I implement a class that provides an iterator for iterating over a Doubly-LinkedList? This should be implemented as a private inner class within the Doubly-LinkedList class.
private class Iterator<T> iterator(){
for(i = 0; list.size() > 20; i++){
System.out.println("Using the iterator approach (numbers > 20) your list is: ")
}

I don't know about your Doubly-LinkedList class. But it may be something like this.
public Iterator<T> iterator() {
return new Iterator<T>() {
Node<T> node = head;
#Override
public boolean hasNext() {
return node != null;
}
#Override
public T next() {
T value = node.value;
node = node.next;
return value;
}
};
}

Related

How can I change my Iterator to be a Fast-fail Iterator?

I'm trying to understand how to modify the Iterator of my Linked List to be fail-fast.
I understand what it means for an Iterator to be fail-fast, but I don't know how exactly should I change my implementation to achieve this behavior.
I was thinking about adding a key so for every add, but I don't think it is good enough. It is the first time I'm trying to implement a fail-fast iterator, and I would really appreciate any hint.
My code:
package GenericLinkedList;
import java.util.Iterator;
public class GenericLinkedList<E> implements Iterable<E> {
private Node<E> head;
public void pushFront(E data){
head = new Node<>(data, head);
}
public E popFront(){
E dataHead = head.data;
head = head.next;
return dataHead;
}
public int size(){
int counter = 0;
for(E element : this){
++counter;
}
return counter;
}
public boolean isEmpty(){
return (null == head);
}
public Iterator<E> find(E data){
IteratorIMP iter = new IteratorIMP(head);
for(E element : this){
if(element.equals(data)){
return iter;
}
iter.next();
}
return null;
}
public static <E> GenericLinkedList<E> merge(GenericLinkedList<E> firstList, GenericLinkedList<E> secondList){
GenericLinkedList<E> mergeList = new GenericLinkedList<E>();
for(E element : firstList){
mergeList.pushFront(element);
}
for(E element : secondList){
mergeList.pushFront(element);
}
return newReverse(mergeList);
}
public static <E> GenericLinkedList<E> newReverse(GenericLinkedList<E> list){
GenericLinkedList<E> reverseList = new GenericLinkedList<E>();
for(E element : list){
reverseList.pushFront(element);
}
return reverseList;
}
private static class Node<T> {
private Node<T> next;
private T data;
private Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
}
private class IteratorIMP implements Iterator<E> {
Node<E> node;
private IteratorIMP(Node<E> start){
node = start;
}
#Override
public boolean hasNext() {
return (node != null);
}
#Override
public E next() {
E data = node.data;
node = node.next;
return data;
}
}
#Override
public Iterator<E> iterator() {
IteratorIMP iter = new IteratorIMP(head);
return iter;
}
}
Fail-fast implementation of the Iterator insures that it would raise an exception if there's an evidence that the collection is being structurally modified (an element was added or removed) during the iteration process, because in such a case, iterator might not be able to reflect the actual state of the collection.
The common approach is to introduce two counters of modifications:
one as the instance field of the list modCount, which would be incremented whenever list gets modified via pushFront(), popFront(), etc.
another in the Iterator - expectedModCount.
If during the next() call turns out that modCount and expectedModCount variables are not equal, that means that there has been a modification after the iterator was created. In such a case, fail-fast Iterators from the JDK would throw ConcurrentModificationException.
public class GenericLinkedList<E> implements Iterable<E> {
private Node<E> head;
private int modCount;
public void pushFront(E data) {
modCount++; // list is being modified - incrementing the count
head = new Node<>(data, head);
}
public E popFront() {
modCount++; // list is being modified - incrementing the count
E dataHead = head.data;
head = head.next;
return dataHead;
}
// ...
private class IteratorIMP implements Iterator<E> {
private Node<E> node;
private final int expectedModCount;
private IteratorIMP(Node<E> start) {
this.node = start;
this.expectedModCount = GenericLinkedList.this.modCount;
}
// ...
#Override
public E next() {
if (expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
E data = node.data;
node = node.next;
return data;
}
}
}

Sorted Stack in Java

I'm trying to implement a stack that keeps the items in a sorted manner and returns the least element in every pop. I'm using two stacks to implement the sorted stack.
Here's my implementation of the plain vanilla stack.
public class Stack<T> implements Iterable{
private Node head;
#Override
public Iterator iterator() {
return new StackIterator();
}
private class Node<T extends Comparable<T>>{
private T data;
private Node next;
public Node(T data){
this.data = data;
next = null;
}
public int compareTo(T other){
return data.compareTo(other);
}
}
private class StackIterator<T> implements Iterator<T> {
Node current = head;
#Override
public boolean hasNext() {
return (current != null);
}
#Override
public T next() {
T item = (T) current.data;
current = current.next;
return item;
}
}
public void push(T item){
Node p = new Node((Comparable) item);
if(head == null){
head = p;
return;
}
p.next = head;
head = p;
}
public T pop(){
if(head == null){
System.out.println("Popping off an empty stack!!!");
System.exit(-1);
}
T item = (T) head.data;
head = head.next;
return item;
}
}
This stack is used in the SortedStack. Here's the partial code.
public class SortedStack<T> {
private int size;
private Stack<T> s1;
private Stack<T> s2;
public SortedStack(){
s1 = new Stack<>();
s1 = new Stack<>();
size = 0;
}
public void push(T item){
for (Iterator<T> iter = s1.iterator(); iter.hasNext(); iter.next()){
if (iter.compareTo(item) > 0){
s2.push(s1.pop());
}else if(iter.compareTo(item) < 0){
s1.push(item);
break;
}else{
s1.push(item);
break;
}
}
for (Iterator<T> iter = s2.iterator(); iter.hasNext(); iter.next()){
s1.push(s2.pop());
}
}
public T pop(){
}
}
The problem is the T(Object) comparison of the nodes doesn't get resolved in the SortedStack. The compareTo doesn't work. This is understandably because of the fact that Node is an inner private class of Stack. My question is how can I expose the compareTo method of the Node class to the SortedStack for implementing it's logic without indiscriminately making everything public?
You have many mistakes in your code.
For example, why are you trying to compare an iterator to an item?
Also, the logic is broken: you compare an item being inserted to s1's head, and then push it to the tail.
As long as the first item inserted is the smallest of all, all the others will always end up in the insertion order.
Consider inserting 0, then 3, then 1 for example.
To answer your question, you want your extends Comparable<T> type boundary on the SortedStack declaration, not on Node.
Node does not need to be Comparable at all.
If this is not for homework, just use TreeSet instead.

java iterator with index parameter

hi a normal iterator for a LinkedList would be the following, however, how do we build an iterator that returns an iterator starting at a specified index? How do we build:
public Iterator<E>iterator(int index)???
thanks!
normal Iterator:
public Iterator<E> iterator( )
{
return new ListIterator();
}
private class ListIterator implements Iterator<E>
{
private Node current;
public ListIterator()
{
current = head; // head in the enclosing list
}
public boolean hasNext()
{
return current != null;
}
public E next()
{
E ret = current.item;
current = current.next;
return ret;
}
public void remove() { /* omitted because optional */ }
}
Well you could just call the normal iterator() method, then call next() that many times:
public Iterator<E> iterator(int index) {
Iterator<E> iterator = iterator();
for (int i = 0; i < index && iterator.hasNext(); i++) {
iterator.next();
}
return iterator;
}
This is kick-off example how to implement such iterator, but it's advised also to create or extend appropriate interface and make this object implementing this interface for convention.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IterableObject {
private List<String> values = new ArrayList<String>();
public Iterator<String> getIterator(final int index) {
Iterator<String> it = new Iterator<String>() {
private int current = index;
#Override
public void remove() {
// TODO Auto-generated method stub
}
#Override
public String next() {
String value = values.get(current);
current++;
return value;
}
#Override
public boolean hasNext() {
if(values.size() > current){
return true;
}else{
return false;
}
}
};
return it;
}
}
UPDATE
According to comments I've written an Iterator for LinkedList
public Iterator<String> getIterator(final int index) {
Iterator<String> it = new Iterator<String>() {
private Object currentObject = null;
{
/*initialize block where we traverse linked list
that it will pointed to object at place index*/
System.out.println("initialize" + currentWord);
for(int i = 0; currentObject.next != null && i < index; i++, currentObject = currentObject.next)
;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
#Override
public String next() {
Object obj = currentObject.next;
currentObject = currentObject.next;
return obj;
}
#Override
public boolean hasNext() {
return currentObject.next != null;
}
};
return it;
}
Because Iterator is object of Anonymous class we can't use constructor but can initialise it in initialise block look at this answer: https://stackoverflow.com/a/362463/947111 We traverse it once at the beginning (sorry for C style) so it will point to currentObject. All remain code is self explained.

generic list java with comparable items

So, I got this comparable class:
public class JakeInteger implements Comparable<JakeInteger>{
private int value;
public JakeInteger(int value){
this.value = value;
}
#Override
public int compareTo(JakeInteger other) {
if (other.getValue() < value)
return -1;
if (other.getValue() > value)
return 1;
return 0;
}
public String toString(){
return String.valueOf(value);
}
public int getValue(){return value;}
I think I've got it right...
Then I have my own linked list of generic objects: (no need to read all of it)
public class GenericList<Type extends Comparable> implements Iterable<Comparable>{
private Node first = null;
private int length = 0;
#Override
public Iterator<Comparable> iterator() {return new ListIterator();}
private class ListIterator implements Iterator<Comparable>{
private Node current = first;
#Override
public boolean hasNext() {return current != null;}
public Node getCurrentNode(){
return current;
}
#Override
public Comparable next() {
Comparable item = current.item;
current = current.next;
return item;
}
}
private class Node{
Comparable<Type> item;
Node next;
}
public boolean isEmpty(){
if (first == null)
return true;
return false;
}
public void prepend(Comparable item){
Node second = first;
first = new Node();
first.item = item;
first.next = second;
length++;
}
public void append(Comparable item){
if (length == 0){
prepend (item);
return;
}
Node last = first;
for (int i = 0; i<length-1; i++)
last = last.next;
last.next = new Node();
last.next.item = item;
length++;
}
public Comparable first(){
return first.item;
}
public Comparable pop(){//rest
Comparable oldFirst = first.item;
first = first.next;
return oldFirst;
}
public int getLength(){
return length;
}
// it
public Comparable getByIndex(int Index){
if (Index > this.length - 1)return null;
Iterator<Comparable> it = iterator();
for (int i = 0; i < Index-1; i++){
it.next();
}
return it.next();
}
public Node getNodeByIndex(int Index){
Node node = first;
for (int i = 0; i < Index; i++)
node = node.next;
return node;
}
public void bubbleSort(){
if (length <= 0)
return;
Node tempNode = first;
int R = length -2;
boolean swapped = true;
while (R >= 0 && swapped){
swapped = false;
for (int i = 0; i <= R; i++){
//if(tempNode.item.compareTo((Type) tempNode.next.item) )
}
}
}
private void swapWithNext(Node a){
Comparable itema = a.item;
a.item = a.next.item;
a.next.item = itema;
}
So far everything works fine, but now, when I'm trying to implement a bubble sort , the item.compareTo() doesn't exist. The way I see it the Item should always have implemented the comparable interface and have access to this method. What am I doing wrong?
Change the implements clause of yourGenericList` from:
public class GenericList<Type extends Comparable> implements Iterable<Comparable>{
To:
public class GenericList<Type extends Comparable<Type>> implements Iterable<Type>{
Just using Comparable is incomplete by itself; you need to say what it should be able to compare against. An in your case, that should be the type variable Type.
Throughout your class, you should also change Comparable to Type, and in the inner class ListIterator, you should also define a type variable (but to avoid confusion, don't call it Type but something else like Type2, because it will be independent from the type variable Type in GenericList)
public Iterator<Type> iterator() {return new ListIterator<Type>();}
private class ListIterator<Type2 extends Comparable<Type2>> implements Iterator<Type2>{
public Type2 next() {
// ...
}
// ...
public void prepend(Type2 item){
// ...
}
public void append(Type2 item){
// ...
}
public Type2 first(){
// ...
public Type2 pop(){
// ...

How to find the max/min element of linked list

I have a doubly linked list in my case. And I want to find the max and min element. So I want to use the Collections to find it. Here is my code below for Node first:
public class Node<T> {
Node<T> prev;
Node<T> next;
T data;
public Node(T _data)
{
data = _data;
prev = null;
next = null;
}
public Node(T _data, Node<T> _prev, Node<T> _next)
{
data = _data;
prev = _prev;
next = _next;
}
T getData()
{
return data;
}
public void setNext(Node<T> _next)
{
next = _next;
}
public void setPrev(Node<T> _prev)
{
prev = _prev;
}
public Node<T> getNext()
{
return next;
}
public Node<T> getPrev()
{
return prev;
}
}
And here is my Doubly Linked List class:
public class DoublyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
int listCount = 0;
public void traverseF()
{
Node<T> temp = head;
while(temp != null)
{
System.out.print(temp.getData() + " ");
temp = temp.getNext();
}
}
public void traverseB()
{
Node<T> temp = tail;
while(temp != null)
{
System.out.print(temp.getData() + " ");
temp = temp.getPrev();
}
}
public void insertFirst(T data)
{
Node<T> temp = new Node<T>(data);
if(head == null)
{
head = temp;
tail = temp;
temp.setNext(null);
temp.setPrev(null);
}
else
{
temp.setNext(head);
head.setPrev(temp);
head = temp;
}
}
}
So, my main code is:
import java.util.Collections;
public class glavna {
public static void main(String[] args) {
DoublyLinkedList<Integer> DLL = new DoublyLinkedList<Integer>();
DLL.insertFirst(32);
DLL.insertFirst(22);
DLL.insertFirst(55);
DLL.insertFirst(10);
DLL.traverseF();
Integer max = Collections.max(DLL);
}
}
How exactly do I call the Collections.max or Collections.min method? Isn't the list only necessary to find the max/min elements?
public T getMin()
{
Node<T> temp = head;
T min = head.getData();
while(temp.getNext() != null)
{
if(temp.getData() < min) // error
{
//min = temp.getData();
}
}
}
To implement getMin with generics you need to be able to compare them. You can, for instance, provide a custom Comparator to your method:
public T getMin(Comparator<? super T> comparator) {
Node<T> temp = head.getNext();
T min = head.getData();
while(temp != null) {
T candidateValue = temp.getData();
if (comparator.compare(candidateValue, min) < 0) { // equivalent to candidate < min
min = candidateValue;
}
temp = temp.getNext();
}
return min;
}
Then, calling your method for Integer :
getMin(new Comparator<Integer>() {
#Override
public int compare(Integer arg0, Integer arg1) {
return arg0.compareTo(arg1);
}
});
Another approach is to make your list only keep Comparable items :
public class DoublyLinkedList<T extends Comparable<? super T>> {
and then have your getMin() method use compareTo method :
public T getMin() {
Node<T> temp = head.getNext();
T min = head.getData();
while(temp != null) {
T candidateValue = temp.getData();
if (candidateValue.compareTo(min) < 0) { // equivalent to candidate < min
min = candidateValue;
}
temp = temp.getNext();
}
return min;
}
Second approach is less verbose, as Integer is Comparable (i.e. implements Comparable for you already), so you won't need to change any other code.
You list is not a Collection, so you cannot use Collections with it.
The Collections.max method expects an argument which implements Collection. The easiest way would probably be to extend AbstractCollection and add these methods:
#Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private Node<T> node = head;
#Override
public boolean hasNext() {
return node != null;
}
#Override
public T next() {
T next = node.data;
node = node.getNext();
return next;
}
};
}
#Override
public int size() {
int size = 0;
Node<T> node = head;
while (node != null) {
size++;
node = node.getNext();
}
return size;
}

Categories

Resources