LinkedList自己实现(追加,插入,删除,遍历)
程序员文章站
2022-06-04 19:28:18
...
java1.8之前是双向循环链表,
java1.8之后是双向不循环链表
public class MyLinkedList<E> {
private Node head;
private int size;
private class Node {
E data;
Node next; //后一个
Node prev; //前一个
public Node(E e){
data = e;
}
};
/**
* 追加元素方法
*/
public boolean add( E e ){
if( head == null ){
//添加第一个元素
head = new Node(e);
//创建循环关系
head.next = head;
head.prev = head;
size++;
return true;
}else{
Node last = head.prev;
Node node = new Node(e);
head.prev = node;
last.next = node;
node.prev = last;
node.next = head;
size++;
return true;
}
}
/**
* 插入元素
*/
public boolean add( int index, E e ){
Node node = find(index);
Node next = node;
Node prev = node.prev;
node = new Node(e);
prev.next = node;
node.next = next;
next.prev = node;
node.prev = prev;
size++;
return true;
}
/**
* 删除元素
*/
public E remove(int index){
if( index < 0 || index >= size ){
throw new IndexOutOfBoundsException();
}
Node node = find(index);
E e = node.data;
node.prev.next = node.next;
node.next.prev = node.prev;
if( index == 0 ){ //删除头
head = node.next;
}
//去掉引用
node.next = null;
node.prev = null;
size--;
return e;
}
/**
* toString
*/
public String toString(){
if( head == null ){
return "[]";
}
StringBuilder stb = new StringBuilder("[");
stb.append(head.data);
Node node = head.next;
for( int i = 1; i < size; i++ ){
stb.append(",").append(node.data);
node = node.next;
}
stb.append("]");
return stb.toString();
}
/**
* 公共方法
* @param index
* @return
*/
private Node find(int index) {
Node node;
//查找插入位置
if( index>size>>1 ){ //反向查找
node = head.prev;
for( int i = size-1; i > index; i-- ){
node = node.prev;
}
}else{ //正向查找
node = head;
for( int i = 0; i < index; i++ ){
node = node.next;
}
}
return node;
}
}