package com.briup.day15.mylist;
public class MyLinkedList {
private class Node {
// 存放元素的值
private Object data;
// 存放上一个节点
private Node prev;
// 存放下一个节点
private Node next;
public Node(Node prev,Object data, Node next) {
this.prev = prev;
this.data = data;
this.next = next;
}
}
//头节点
private Node head;
//数据
private Object element;
//尾节点
private Node tail;
//集合中元素个数
private int size;
public void add(Object o) {
//获取到尾节点
Node tailNode = tail;
//把当前数据包装成Node节点
Node newNode = new Node(tailNode,o,null);
tail = newNode;
if(tailNode == null) {
//如果尾节点为null,说明这个链表从来没有使用过
//则当前节点就是头节点
head = newNode;
}else {
tailNode.next = newNode;
newNode.prev = tailNode;
}
size++;
}
public void add(int index, Object o) {
checkIndex(index);
Node prevNode = findNode(index).prev;
Node nextNode = findNode(index);
Node newNode = new Node(prevNode,o,nextNode);
prevNode.next = newNode;
nextNode.prev = newNode;
size++;
}
public Object remove(int index) {
checkIndex(index);
Node oldNode = findNode(index);
Object oldValue = oldNode.data;
unLink(oldNode);
return oldValue;
}
//给我一个节点,我把它从链表中删除,断开连接
private void unLink(Node targetNode) {
Node prevNode = targetNode.prev;
Node nextNode = targetNode.next;
if(prevNode == null) {
//说明targetNode是头节点
head = nextNode;
}else {
prevNode.next = nextNode;
}
if(nextNode == null) {
//说明targetNode是尾节点
tail = prevNode;
}else {
nextNode.prev = prevNode;
}
targetNode = null;
size--;
}
private Node findNode(int index) {
checkIndex(index);
Node currentNode;
if(index<(size>>1)) {
currentNode = head;
//从前往后找
for(int i = 0;i<index;i++) {
currentNode = currentNode.next;
}
}else {
currentNode = tail;
//从后往前找
for(int i = size-1;i>index;i--) {
currentNode = currentNode.prev;
}
}
return currentNode;
}
public Object get(int index) {
checkIndex(index);
return findNode(index).data;
}
public int size() {
return size;
}
private void checkIndex(int index) {
if(index<0 || index>=size) {
throw new RuntimeException("MyLinkedList索引越界,index="+index);
}
}
}
简单实现LinkedList
最新推荐文章于 2021-07-29 18:32:45 发布