public class MyLinkedList { private Node head; //整个链表的头结点 private int listSize; public MyLinkedList() { head = new Node(0); head.next = null; } //内部类,来表示节点 private static class Node { public Object data; //节点的数据域 public Node next; //节点指向下一个节点的指针 public Node(Object data) { this.data = data; } public Node() { data = null; } } //在制定的位置插入指定的元素 public void add(int index, Object element) { if(index >(Integer)head.data || index<0) { throw new IndexOutOfBoundsException("index:" + index); } Node newNode = new Node(element); Node p = head; for(int i=0; i<index; i++) { p = p.next; } newNode.next = p.next; p.next = newNode; head.data = (Integer)head.data +1; } public boolean add(Object element) { add((Integer)head.data, element); //将制定元素添加到链表尾 return false; } //清除链表 public void clear() { head.data = 0; head.next = null; } //是否包含指定的元素 public boolean contains(Object o) { Node p = head; while(p != null){ p = p.next; if(p.data.equals(o)) return true; } return false; } //获取指定下标的元素 public Object get(int index) { if(index > (Integer)head.data || index < 0) { throw new IndexOutOfBoundsException("index:" + index); } Node p = head; int i = 0; while(p != null) { p = p.next; if(i == index) { return p.data; } i++; } return null; } //返回指定元素首次在链表出现的位置 public int indexOf(Object o) { Node p = head; int i = 0; while(p != null) { p = p.next; if(p.data.equals(o)) { return i; } i++; } return -1; } public boolean isEmpty() {//判断链表是否为空 return (Integer)head.data == 0; } public int size() {//返回链表的长度 return (Integer)head.data; } //在制定下标的位置插入指定的元素 public Object set(int index, Object element) { if(index > (Integer)head.data || index < 0) { throw new IndexOutOfBoundsException("index:" + index); } Node p = head; int i = 0; Object temp; while(p != null) { if(i == index) { temp = p.data; p.data = element; return temp; } p = p.next; i++; } return null; } //删除指定的元素 public boolean remove(Object element) { boolean flag = false; Node p = head; if((Integer)head.data == 0) return false; while(p.next != null) { if(p.next.data.equals(element)) { p = p.next.next; flag = true; } p = p.next; } return flag; } //删除指定下标的元素,并返回删除的元素 public Object remove(int index) { if(index > (Integer)head.data || index < 0) { throw new IndexOutOfBoundsException("index:" + index); } Node p = head; int i = 0; Object temp; while(p != null) { if(i == index) { temp = p.next.data; p.next = p.next.next; head.data = (Integer)head.data - 1; return temp; } p = p.next; i ++; } return null; } public void print(MyLinkedList list) { for(int i=0; i<list.size(); i++) { System.out.print(list.get(i) + " "); } System.out.println(); } }