LinkList
package com.lanh;
public class LinkList<E> implements List<E>{
private static final int ELEMENT_NOT_FOUND = -1;
private int size;
private Node first;
private static class Node<E>{
E element;
Node<E> next;
public Node(E element,Node<E> next){
this.element = element;
this.next = next;
}
}
public void clear() {
size=0;
first = null;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size==0;
}
public boolean contains(E element) {
return indexOf(element) == ELEMENT_NOT_FOUND;
}
public void add(E element) {
add(size,element);
}
public E get(int index) {
return node(index).element;
}
public E set(int index, E element) {
E old = node(index).element;
node(index).element = element;
return old;
}
public void add(int index, E element) {
rangeCheckForAdd(index);
if (index==0){
first = new Node<>(element,first);
}else {
Node<E> prev = node(index-1);
prev.next = new Node<>(element,prev.next);
}
size++;
}
public E remove(int index) {
rangeCheck(index);
Node<E> node = first;
if (index==0){
first = first.next;
}else {
Node<E> prev = node(index-1);
node = prev.next;
prev.next = node.next;
}
size--;
return node.element;
}
public int indexOf(E element) {
if(element==null){
Node<E> node = first;
for (int i=0;i<size;i++){
if (node.element==null) return i;
node = node.next;
}
}else {
Node<E> node = first;
for (int i=0;i<size;i++){
if(element.equals(node.element)) return i;
node = node.next;
}
}
return ELEMENT_NOT_FOUND;
}
public Node<E> node(int index){
rangeCheck(index);
Node<E> node = first;
for (int i=0;i<index;i++){
node = node.next;
}
return node;
}
private void outOfBounds(int index) {
throw new IndexOutOfBoundsException("Index:" + index + ",Size" + size);
}
private void rangeCheck(int index) {
if (index < 0 || index >= size) {
outOfBounds(index);
}
}
private void rangeCheckForAdd(int index) {
if (index < 0 || index > size) {
outOfBounds(index);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("size=").append(size).append(",[");
Node<E> node = first;
for (int i=0;i<size;i++){
if (i!=0){
sb.append(",");
}
sb.append(node.element);
node = node.next;
}
sb.append("]");
return sb.toString();
}
}