直接上代码
package com.mydemo.writeCases;
public class ILinkedList<E> {
private class INode{
private E e;
private INode next;
public INode(){
}
public INode(E e){
this.e = e;
}
public INode(E e,INode next){
this.e = e;
this.next = next;
}
@Override
public String toString(){
return this.e == null ? "null" : this.e.toString();
}
}
private INode dummyHead;
private int size;
public ILinkedList(){
this.dummyHead = new INode();
this.size = 0;
}
public int getSize(){
return this.size;
}
public void add(E e, int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("角标越界");
}
INode prev = this.dummyHead;
for (int i = 0; i < index; i++) {
prev = prev.next;
}
prev.next = new INode(e,prev.next);
size++;
}
public void addFirst(E e){
this.add(e,0);
}
public void addLast(E e){
this.add(e,size);
}
public E remove(int index){
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("角标越界");
}
INode prev = this.dummyHead;
for (int i = 0; i < index; i++) {
prev = prev.next;
}
INode targetNode = prev.next;
prev.next = targetNode.next;;
targetNode.next = null;
size--;
return targetNode.e;
}
public E removeFirst(){
return remove(0);
}
public E removeLast(){
return remove(size-1);
}
public E get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("角标越界");
}
INode prev = this.dummyHead;
for (int i = 0; i < index; i++) {
prev = prev.next;
}
return prev.next.e;
}
public E getFirst(){
return get(0);
}
public E getLast(){
return get(size-1);
}
public void set(E e,int index){
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("角标越界");
}
INode prev = this.dummyHead;
for (int i = 0; i < index; i++) {
prev = prev.next;
}
prev.next.e = e;
}
public boolean contains(E e) {
INode cur = dummyHead.next;
while (cur != null) {
if (cur.e.equals(e)) {
return true;
}
cur = cur.next;
}
return false;
}
@Override
public String toString(){
StringBuilder stringBuilder = new StringBuilder("");
for (INode cur = dummyHead.next; cur != null; cur = cur.next) {
stringBuilder.append("[" + cur + "]");
}
return stringBuilder.toString();
}
}