实现代码
public class LinkedList<E>{
private class Node{
private E e;
private Node next;
public void Node(E e, Node next){
this.e = e;
this.next = next;
}
public Node(E e){
this(e, next);
}
public Node(){
this(null, null);
}
public String toString(){
return e.toString;
}
}
private Node dummyhead;
private int size;
public LinkedList(){
dummyhead = new Node(null, null);
size = 0;
}
public int getSize(){
return size;
}
public boolean isEmpty(){
return (size == 0);
}
public void add(int index, E e){
if (index < 0 || index > size){
throw new IllegalArgumentException("Add failed, Illegal index.");
}
Node pre = dummyhead;
for (int i = 0, i < index, i++){
pre = pre.next;
}
Node node = new Node(e);
node.next = pre.next;
pre.next = node;
size ++;
}
public void addFirst(E e){
add(0, e);
}
public void addLast(E e){
add(size ,e);
}
public E get(int index){
if (index < 0 || index > size){
throw new IllegalArgumentException("Get failed, Illegal index.");
}
Node cur = dummyNode.next;
if (int i = 0; i < index; i++){
cur = cur.next;
}
return cur.next;
}
public E getFirst(){
return get(0);
}
public E getLast(){
return get(size - 1);
}
public void set(int index){
if (index < 0 || index > size){
throw new IllegalArgumentException("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 == e){
return true;
}
cur = cur.next;
}
return false;
}
public E delete(int index){
if (index < 0 || index > size){
throw new IllegalArgumentException("Delete failed, Illegal index.");
}
Node pre = dummyhead;
for (int i = 0; i < index; i++){
pre = pre.next;
}
Node ret = pre.next;
pre.next = ret.next;
ret.next = null;
size --;
return ret.e;
}
public E removeFirst(){
return delete(0);
}
public E removeLast(){
return delete(size - 1);
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
Node cur = dummyhead.next;
while (cur != null){
sb.append(cur+"->");
cur = cur.next;
}
sb.append("NULL");
return sb.toString();
}
}
测试类
public class Main {
public static void main(String[] args){
LinkedList<Integer> linkedList = new LinkedList<>();
for(int i = 0 ; i < 5 ; i ++){
linkedList.addFirst(i);
System.out.println(linkedList);
}
linkedList.add(2, 666);
System.out.println(linkedList);
linkedList.delete(2);
System.out.println(linkedList);
}
}