- 节点类
package com.linkedlist.doublelinkedlist;
public class Node {
public int no;
public String name;
public Node next;
public Node pre;
public Node() {
}
public Node(int no, String name){
this.no = no;
this.name = name;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}
- 链表类
package com.linkedlist.doublelinkedlist;
public class DoubleLinkedList {
final Node head = new Node();
public void add(Node node){
Node temp = head;
while(true){
if(temp.next == null){
break;
}
temp = temp.next;
}
temp.next = node;
node.pre = temp;
}
public void addOrderByAsc(Node node){
Node temp = head;
boolean flag = false;
while(true){
if(temp.next == null){
break;
}
if(temp.next.no > node.no){
break;
}else if(temp.next.no == node.no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
System.out.println("节点已经存在!");
}else{
node.next = temp.next;
//判断是否在链表结尾
if(temp.next != null){
temp.next.pre = node;
}
node.pre = temp;
temp.next = node;
}
}
public void list(){
if(head.next == null){
System.out.println("双向链表为空!");
return;
}
Node temp = head.next;
while(temp != null){
System.out.println(temp);
temp = temp.next;
}
}
public void update(Node node){
if(head.next == null){
System.out.println("该双向链表为空!");
return;
}
Node temp = head.next;
boolean flag = false;
while(temp != null){
if(temp.no == node.no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
temp.name = node.name;
}else{
System.out.println("该节点不存在!");
}
}
public void del(int no){
if(head.next == null){
System.out.println("该双向链表为null");
return;
}
Node temp = head.next;
boolean flag = false;
while(temp != null){
if(temp.no == no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
temp.pre.next = temp.next;
if(temp.next != null){
temp.next.pre = temp.pre;
}
}else{
System.out.println("节点不存在!");
}
}
}