最简单的Java LinkedList类的实现
1、SimpleLinkedList 细节概述
1、SimpleLinkedList 使用双向链表实现,包含一些集合常用操作方法
2、node类,可以是个私有嵌套类。一个节点包含数据以及前一个节点的链和到下一个节点的链。
3、SimpleLinkedListIterator类,实现Iterator,实现next,hasNext方法
2、源码
package org.folio.rest.base;
import java.util.Iterator;
/**
* @ProjectName: com.ketu.ilasfolio
* @Package: org.folio.rest.base
* @ClassName: SimpleLinkedList
* @Author: zhaokq
* @Description:
* @Date: 2022/1/24 09:29
*/
public class SimpleLinkedList<T> implements Iterable<T> {
public SimpleLinkedList() {
beginNode = new Node<>(null,null,null);
endNode = new Node<>(null,beginNode,null);
beginNode.next = endNode;
size = 0;
}
private int size;
private Node<T> beginNode;
private Node<T> endNode;
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean add(T data) {
add(size(), data);
return true;
}
public void add(int i, T data) {
addBefore(getNode(i,0,size()),data);
}
public void addBefore(Node<T> p, T data) {
Node<T> newNode = new Node<T>(data, p.prev, p);
newNode.prev.next = newNode;
p.prev = newNode;
size++;
}
public T remove(int i) {
return remove(getNode(i));
}
private T remove(Node<T> node) {
node.next.prev = node.prev;
node.prev.next = node.next;
size--;
return node.data;
}
public T get(int i) {
return getNode(i).data;
}
public Node<T> getNode(int i){
return getNode(i,0,size()-1);
}
public Node<T> getNode(int i,int lower,int upper){
if(i<lower||i>upper){
throw new IndexOutOfBoundsException();
}
Node<T> t;
if(i<size/2){
t = beginNode.next;
for (int j = 0; j < i; j++) {
t = t.next;
}
}else {
t = endNode;
for (int j = size(); j > i; j--) {
t = t.prev;
}
}
return t;
}
private class Node<T> {
public T data;
public Node<T> prev;
public Node<T> next;
public Node(T data, Node<T> prev, Node<T> next) {
this.data = data;
this.prev = prev;
this.next = next;
}
}
@Override
public Iterator iterator() {
return new SimpleLinkedListIterator();
}
private class SimpleLinkedListIterator implements Iterator<T> {
private Node<T> current = beginNode.next;
@Override
public boolean hasNext() {
return current != endNode;
}
@Override
public T next() {
T data = current.data;
current = current.next;
return data;
}
}
}
3、测试
public static void main(String[] args) {
SimpleLinkedList<String> simpleLinkedList = new SimpleLinkedList();
simpleLinkedList.add("a");
simpleLinkedList.add("b");
simpleLinkedList.add("c");
simpleLinkedList.add("d");
System.out.println(simpleLinkedList.size());
for (int i = 0; i < simpleLinkedList.size; i++) {
String data = simpleLinkedList.get(i);
System.out.println(data);
}
for (String s : simpleLinkedList) {
System.out.println(s);
}
}
4、总结
简单实现双向链表,学习LinkedList原理可以参考,有问题或者建议可评论区留言讨论