LinkedListIterable
import java.util.Iterator;
public class LinkedListIterable implements Iterable {
@SuppressWarnings("ClassCanBeStatic")
private class Node {
T data;
Node next;
public Node(T data){
this.data = data;
}
public Node(T data, Node next){
this.data = data;
this.next = next;
}
}
@SuppressWarnings("ClassCanBeStatic")
public class LLIterator implements Iterator {
private LinkedListIterable ll;
private LinkedListIterable.Node curr;
public LLIterator(LinkedListIterable ll){
this.ll = ll;
curr = null;
}
@Override
public boolean hasNext(){
if (curr == ll.tail && ll.tail != null) return false;
return true;
}
@Override
public U next(){
if (curr == null)
curr = ll.head;
else curr = curr.next;
return curr.data;
}
}
private Node head, tail;
private int count = 0;
public int size(){
return count;
}
@Override
public Iterator iterator(){
return new LLIterator(this);
}
// If the LL is empty, create a new node,
// that new node is head and tail.
// If LL is not empty, prepend as before.
public void prepend(E d){
if (head == null)
tail = head = new Node<>(d);
else
head = new Node<>(d, head);
count++;
}
public void append(E d){
if (head == null)
tail = head = new Node<>(d);
else
tail = tail.next = new Node<>(d);
count++;
}
public boolean contains(E d){
Node curr = head;
while (curr != null && curr.data != d)
curr = curr.next;
return curr != null;
}
public E get(int idx){
if (idx >= count || idx < 0) throw new IndexOutOfBoundsException();
Node curr = head;
for (int i = 0; i < idx; i++){
curr = curr.next;
}
return curr.data;
}
// Insert d into the linked list at index idx
// Find the node *before* where the new node is
// to be inserted. Create the new node and update
// references as necessary.
public void insert(int idx, E d){
if (idx > count || idx < 0) throw new IndexOutOfBoundsException();
if (idx == 0)
prepend(d);
else {
Node curr = head;
for (int i = 0; i < idx-1; i++){
curr = curr.next;
}
Node newNode = new Node(d, curr.next);
curr.next = newNode;
}
count++;
}
@Override
public String toString(){
String retVal = "Linked list of size: " + count + '\n';
for (Node temp = head; temp != null; temp = temp.next)
retVal += temp.data + " ";
/*Node curr = head;
while(curr != null){
retVal += curr.data + " ";
curr = curr.next;
}*/
return retVal;
}
// Testing our LL:
public static void main(String[] args){
LinkedListIterable ll = new LinkedListIterable();
ll.prepend(10);
ll.prepend(45);
ll.prepend(23);
System.out.println("Contains 45? " + ll.contains(45));
System.out.println("Contains 37? " + ll.contains(37));
System.out.println(ll);
ll.append(19);
System.out.println(ll);
System.out.println("First element: " + ll.get(0));
System.out.println("Last element: " + ll.get(3));
// System.out.println("Last element: " + ll.get(4));
ll.insert(4, 15);
System.out.println(ll);
for (Integer i : ll)
System.out.println(i);
}
}