/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
static LinkedList<String> list = new LinkedList<String>();
{
Ideone.test();
}
public static void test() {
list.add("oi");
list.add("ola");
list.add("hello");
list.remove("hello");
}
public static class LinkedList<V> {
private int size;
private Node<V> root;
private Node<V> last;
public void add(V value) {
System.
out.
println("add('" + value
+ "')"); if(root == null) {
size++;
root = last = new Node<V>(value);
return;
}
System.
out.
println("addNext('" + value
+ "')"); size++;
Node<V> next = new Node<V>(value);
last.next = next;
last = last.next;
}
public void remove(V value) {
System.
out.
println("remove('" + value
+ "')"); if(root == null) {
return;
}
if(root.getValue().equals(value)) {
size--;
if(root.next == null) {
root = last = null;
return;
}
root = root.next;
return;
}
removeNext(root, value);
}
private void removeNext(Node<V> newRoot, V value) {
System.
out.
println("removeNext('" + value
+ "')"); if(newRoot.next == null) {
return;
}
if(newRoot.next.getValue().equals(value)) {
size--;
if(newRoot.next == null) {
newRoot.next = null;
last = newRoot;
return;
}
newRoot.next = newRoot.next.next;
return;
}
removeNext(newRoot.next, value);
}
public V get(int index) {
System.
out.
println("get('" + index
+ "')"); if(root == null || index > (size - 1)) {
return null;
}
if(index == (size - 1)) {
return last.getValue();
}
int count = 0;
if(count == index) {
System.
out.
println("getNextValue('" + index
+ "=" + root.
getValue() + "')"); return root.getValue();
}
return getNext(root.next, count+1, index);
}
private V getNext(Node<V> next, int count, int index) {
System.
out.
println("getNext('" + count
+ "==" + index
+ "')"); if(next == null) {
System.
out.
println("getNextValue('" + index
+ "=null')"); return null;
}
if(count == index) {
System.
out.
println("getNextValue('" + index
+ "=" + next.
getValue() + "')"); return next.getValue();
}
return getNext(next.next, count+1, index);
}
public int getSize() {
return size;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i = 0; i < size; i++) {
sb.append(i).append("=").append(get(i));
if(i != (size - 1)) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
return root.printNodeAndChilds();
}
}
public static class Node<V> {
private V value;
public Node<V> next;
public Node<V> previous;
public Node(V value) {
this.value = value;
}
public V getValue() {
return value;
}
public String printNodeAndChilds
() { StringBuilder sb = new StringBuilder();
sb.append("[0=").append(value);
Node<V> nextNode = next;
int count = 1;
while(nextNode != null) {
sb.append(", ").append(count).append("=").append(nextNode.getValue());
nextNode = nextNode.next;
count++;
}
sb.append("]");
return sb.toString();
}
return value.toString();
}
}
}