这个错误如题很奇怪,dubug下提示类中的Node类空指针,而直接运行就不会报错误,图如下
正常执行
dubug运行
内部实现代码如下
package utils; /** * @author yqs * @description * @time 2019/7/13 18:09 */ public class SingleLinked<E> { private int size; private Node<E> dummyHead; public SingleLinked(){ dummyHead = new Node<>(); } private class Node<E>{ private Node next; private E element; public Node(){ this(null, null); } public Node(E element,Node next){ this.element = element; this.next = next; } @Override public String toString(){ if (element!=null){ return element.toString(); } return null; } } public void addFirst(E e) { dummyHead.next = new Node<>(e,dummyHead.next); size++; } //指定位置添加元素 public void add(E e, int index) { if (index < 0 || index > size) { throw new IllegalArgumentException("index is illegal,add failed"); } Node head = dummyHead; for (int i = 0; i < index; i++) { head = head.next; } head.next = new Node(e,head.next); size++; } public void addLast(E e){ add(e,size); } //在指定位置删除元素 public E remove(int index){ //System.out.println(dummyHead); //存虚拟头结点 Node<E> prev = dummyHead; for (int i = 0; i < index; i++) { prev = prev.next; } //将当前元素存入prev_temp临时变量中 Node<E> prev_temp = prev.next; //将当前元素的前一个节点的next指向当前元素的下一个节点; prev.next = prev_temp.next; //将当前元素的next设置为null等待虚拟机回收 prev_temp.next = null; size--; return prev_temp.element; } public int getSize() { return size; } public boolean isEmpty(){ return size == 0; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { sb.append(dummyHead.next); sb.append(","); dummyHead = dummyHead.next; } return sb.toString(); } }
另外,要是换成双向链表要加一个尾节点,还有要不要在Node类中加一个prev节点指向上一个呢,我看网上有的教程并没有加这个prev,jdk源码加了
cxxyjsj