直接上代码
package com.mydemo.writeCases;
/**
* 简易链表手写实现
* @param <E>
*/
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(){
//"null"处理主要是防止dummyHead.toString被调用抛出空指针(比如IDEA默认dubug时会调用)
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) {
//注意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);
}
//set方法
public void set(E e,int index){
if (index < 0 || index >= size) {
//注意index=size时的情况
throw new IndexOutOfBoundsException("角标越界");
}
INode prev = this.dummyHead;
for (int i = 0; i < index; i++) {
prev = prev.next;
}
prev.next.e = e;
}
//contains方法
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();
}
}