//在链表的index(0-based)位置添加新的元素e //链表中不是一个常用的操作 publicvoidadd(int index, E e){ if (index < 0 || index > size) { thrownew IllegalArgumentException("Add Failed.Illegal index."); }
Node prev = dummyHead; for (int i = 0; i < index; i++) { prev = prev.next; }
prev.next = new Node(e, prev.next); size++; }
publicvoidaddLast(E e){ add(size, e); }
public E get(int index){ if (index < 0 || index >= size) { thrownew IllegalArgumentException("Get Failed.Illegal index"); } Node cur = dummyHead.next; for (int i = 0; i < index; i++) { cur = cur.next; } return cur.e; }
//获取链表的第一个元素 public E getFirst(){ return get(0); }
//获取链表的最后一个元素怒 public E getLast(){ return get(size - 1); }
//修改链表的index元素(0-based)个位置的元素 //不常用的操作 publicvoidset(int index, E e){ if (index < 0 || index >= size) { thrownew IllegalArgumentException("Update Failed.Illegal index"); } else { Node cur = dummyHead.next; for (int i = 0; i < index; i++) { cur = cur.next; } cur.e = e; } }
//查找链表是否存在元素E publicbooleancontains(E e){ Node cur = dummyHead.next; while (cur != null) { if (cur.e.equals(e)) { returntrue; } cur = cur.next; } returnfalse; }
public E remove(int index){ if (index < 0 || index >= size) { thrownew IllegalArgumentException("Update Failed.Illegal index"); } else { 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 E removeFirst(){ return remove(0); }
public E removeLast(){ return remove(size - 1); }
@Override public String toString(){ StringBuilder res = new StringBuilder(); for (Node cur = dummyHead.next; cur != null; cur = cur.next) { res.append(cur + "->"); } res.append("NULL"); return res.toString(); }