双向链表
概念
双向链表中节点拥有上一个节点指针和下一个节点的指针
代码
package com.free.fly.algorithm.linetable;
import java.util.Objects;
/**
* 双向链表
*
* @author freeflying
* @since 1.0
*/
public class DoubleLinkedList {
private Node head;
private int len;
public DoubleLinkedList() {
this.len = 0;
}
private void add(Node node){
len++;
if (head == null){
head = node;
return;
}
Node tempNode = head;
while (tempNode.nextNode != null){
tempNode = tempNode.nextNode;
}
tempNode.nextNode = node;
node.prevNode = tempNode;
}
public void add(Object data){
if (Objects.isNull(data)){
throw new NullPointerException();
}
add(new Node(data));
}
public void remove(Object data){
if (head == null){
return;
}
while (head.data.equals(data)){
len--;
head = head.nextNode;
head.prevNode = null;
}
Node temp = head;
while (temp != null){
Node next = temp.nextNode;
if (Objects.isNull(next)){
break;
}
if (next.data.equals(data)){
len--;
temp.nextNode = next.nextNode;
if (!Objects.isNull(next.nextNode)){
next.nextNode.prevNode = temp;
}
}
temp = temp.nextNode;
}
}
public boolean contains(Object data){
if (Objects.isNull(data)){
return false;
}
Node temp = head;
while (temp != null){
if (temp.data.equals(data)){
return true;
}
temp = temp.nextNode;
}
return false;
}
public int size(){
return len;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node temp = head;
while (temp != null){
sb.append(temp.data + ":");
temp = temp.nextNode;
}
return sb.toString();
}
}
class Node{
Object data;
public Node(Object data) {
this.data = data;
}
Node nextNode;
Node prevNode;
}