# 双向链表的实现

class Node{
public Node next;
public Node prey;
public int data;

public Node(int data){
this.data = data;
}
}

class DoubleList{
public Node last;
public DoubleList(){
this.last = null;
}
//头插法
Node node = new Node(data);
this.last = node;
}else{
}
}

//尾插法
Node node = new Node(data);
this.last = node;
}else{
last.next = node;
node.prey = last;
last = node;
}
}

//任意位置插入,第一个数据节点为0号下标

//检查index合法性
private void checkIndex(int index){
if(index < 0 || index > size()) {
throw new IndexOutOfBoundsException("index越界异常");
}
}
//找对应下标节点
private Node foundIndex(int index){

int count = 0;
while(count < index){
count++;
cur = cur.next;
}
return cur;
}
//首先要找到对应下标节点并检查合法性，checkIndex();foundIndex();
checkIndex(index);
Node node = new Node(data);
Node cur = foundIndex(index);
return  true;
}else if(cur == last){
}
node.next = cur;
node.prey = cur.prey;
cur.prey.next = node;
cur.prey = node;
return true;
}

//求双向链表长度
public int size(){
int count = 0;
return 0;
}
while(cur != null){
cur = cur.next;
count++;
}
return count;
}
//查找是否包含关键字key是否在双向链表当中
public boolean contains(int key){
while(cur != null){
if(cur.data == key){
return true;
}
cur = cur.next;
}
return false;
}
//删除第一次出现关键字为key的节点
public void remove(int key){
while(cur != null){
//头结点
if(cur.data == key && cur == head){
return ;
}
//尾节点
else if(cur.data == key && cur == last){
last = last.prey;
last.next = null;
return ;
}
//中间节点
else if(cur.data == key){
cur.prey.next = cur.next;
cur.next.prey = cur.prey;
return ;
}
cur = cur.next;
}
}
//删除所有值为key的节点
public void removeAllKey(int key){
while(cur != null){
//头结点
if(cur.data == key && cur == head){
}
//尾节点
else if(cur.data == key && cur == last){
last = last.prey;
last.next = null;
}
//中间节点
else if(cur.data == key){
cur.prey.next = cur.next;
cur.next.prey = cur.prey;
}
cur = cur.next;
}
}
//展示双向链表
public void display(){
while(cur != null){
System.out.print(cur.data+" ");
cur = cur.next;
}
System.out.println();
}
//清空双向链表（不允出现内存泄漏）
public void clear(){

while(cur != null){
Node curNext = cur.next;
cur.prey = null;
cur.next = null;
cur = curNext;
}
//防止内存泄漏
this.last = null;
}
}

# 测试

public class TestDamo{
public static void main(String[] args) {
DoubleList doubleList = new DoubleList();
doubleList.display();
System.out.println("长度:"+doubleList.size());
doubleList.display();
doubleList.remove(2);//删除第一次出现data为2的节点
doubleList.display();
doubleList.removeAllKey(3);//删除所有data为3的节点
doubleList.display();
System.out.println("========下面是清空双向链表");
doubleList.clear();
doubleList.display();
}
}

## 测试结果

6 5 4 3 2 1 3

6 5 10 4 3 2 1 3
6 5 10 4 3 1 3
6 5 10 4 1
========下面是清空双向链表

========上面是清空双向链表

©️2019 CSDN 皮肤主题: 技术工厂 设计师: CSDN官方博客