class LinkedList2<E>{
//链表节点
private static class Node<E>{
E item;
Node<E> next;
Node<E> prev;
public Node(E item,Node<E> next,Node<E> prev){
this.item=item;
this.next=next;
this.prev=prev;
}
}
private int size;
private Node<E> first;
private Node<E> last;
//添加
public boolean add(E e){
addAtLast(e);
return true;
}
//在最后位置添加
private void addAtLast(E e){
Node<E> l = last;
Node<E> node = new Node<>(e, null, l);
last = node;
//为空时first=node,不为空时l.next=node
if (l == null) {
first = node;
} else {
l.next = node;
}
size++;
}
//在指定位置添加
public void add(int index,E e){
checkRangeForAdd(index);
if (index == size) {
addAtLast(e);
} else {
//查找出第index个节点,在之前插入
Node<E> l = node(index);
addBeforeNode(e, l);
}
}
//检查是否超过边界
private void checkRangeForAdd(int index) {
if (index >size || index <0) {
throw new IndexOutOfBoundsException("指定的index超过界限");
}
}
// 根据index获取相应的节点
private Node<E> node(int index) {
//index<size/2在前一半中遍历查找,否则从最后查找
if (index < (size>>1)) {
Node<E> cursor = first;
for (int i = 0; i < index; i++) {
cursor = cursor.next;
}
return cursor;
} else {
Node<E> cursor = last;
for (int i = size - 1; i > index; i--) {
cursor = cursor.prev;
}
return cursor;
}
}
//在某个元素之前添加
private void addBeforeNode(E element, Node<E> specifiedNode) {
Node<E> preNode = specifiedNode.prev;
Node<E> newNode = new Node<>(element, specifiedNode, preNode);
if (preNode == null) {
first = newNode;
}else{
preNode.next = newNode;
}
specifiedNode.prev = newNode;
size++;
}
//获取某个节点
public E get(int index) {
checkRange(index);
return node(index).item;
}
//index是否在0~size-1
private void checkRange(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("指定index超过界限");
}
}
//移除index节点
public E remove(int index) {
checkRange(index);
return deleteLink(index);
}
//移除某个节点
public boolean remove(Object o) {
int index = indexOf(o);
if (index < 0){
return false;
}
deleteLink(index);
return true;
}
//获取某个节点的index
public int indexOf(Object element) {
Node<E> cursor = first;
int count = 0;
while (cursor != null) {
if (element != null) {
if (element.equals(cursor.item)) {
return count;
}
}else{
if (cursor.item == null) {
return count;
}
}
count ++;
cursor = cursor.next;
}
return -1;
}
//删除链表的节点
private E deleteLink(int index) {
Node<E> l = node(index);
E item = l.item;
Node<E> prevNode = l.prev;
Node<E> nextNode = l.next;
if (prevNode == null) {
first = nextNode;
}else{
prevNode.next = nextNode;
l.next = null;
}
if (nextNode == null) {
last = prevNode;
}else{
nextNode.prev = prevNode;
l.prev = null;
}
size--;
l.item = null;
return item;
}
//返回链表的大小
public int size(){
return size;
}
}
public class Test {
public static void main(String[] args) {
LinkedList2<String> lk=new LinkedList2<String>();
lk.add("jok");
lk.add("linmin");
lk.add("min");
String s=lk.get(1);
System.out.println(s);
lk.remove(1);
String s1=lk.get(1);
System.out.println(s1);
}
}
集合类LinkedList简单的实现
最新推荐文章于 2023-06-17 10:27:08 发布