//在链表中添加新元素 index=>索引publicvoidadd(int index,E e){//对传入非法值的处理 抛出错误if(index <0|| index > size){thrownewIllegalArgumentException("Add failed. Illegal index.");}
Node prev = dummyHead;for(int i =0; i < index; i ++)
prev = prev.next;
prev.next =newNode(e, prev.next);//代码执行顺序 左 <- 右//维护元素个数
size ++;}
获取元素
//在链表中获得元素publicEget(int index){if(index <0|| index >= size){thrownewIllegalArgumentException("Get failed. Illegal index.");}
Node cur = dummyHead.next;for(int i =0; i < index; i ++)
cur = cur.next;return cur.e;}
修改元素
//在链表中修改新元素publicvoidset(int index,E e){if(index <0|| index > size){thrownewIllegalArgumentException("Set failed. Illegal index.");}
Node cur = dummyHead.next;for(int i =0; i < index; i ++)
cur = cur.next;
cur.e = e;}
存在元素
//查找链表中是否存在元素public boolean contains(E e){
Node cur = dummyHead.next;while(cur !=null){if(cur.e.equals(e))returntrue;else
cur = cur.next;}returnfalse;}
删除元素
//删除链表某一元素publicEremove(int index){if(index <0|| index >= size){thrownewIllegalArgumentException("Remove failed. Illegal index.");}
Node prev = dummyHead;for(int i =0; i < index; i ++){
prev = prev.next;}
Node retNode = prev.next;
prev.next = retNode.next;
retNode.next =null;//触发回收机制
size --;//维护元素个数return retNode.e;}
输出格式
public String toString(){
StringBuilder res =newStringBuilder();
Node cur = dummyHead.next;while(cur !=null){
res.append(cur +"->");
cur = cur.next;}
res.append("END");return res.toString();}
使用链表
publicclassMain{publicstaticvoidmain(String[] args){
LinkedList<Integer> list =newLinkedList<>();//创建整型链表对象}