双向链表中有一个头指针(head),然后每个节点有两个指针分别指向前面一个节点和后面一个节点。
package com.yf;
public class Day11 {
public static void main(String[] args) {
Node A = new Node(1,"yf1");
// System.out.println();
Node B = new Node(2,"yf2");
Node C = new Node(3,"yf3");
DoubleLinkedList list = new DoubleLinkedList();
// list.addToEnd(C);
// list.addToEnd(B);
// list.addToEnd(A);
list.addByOrder(C);
list.addByOrder(B);
list.addByOrder(A);
list.showList();
list.delete(1);
list.showList();
}
}
class Node{
public int id;
public String name;
public Node pre;
public Node next;
public Node(int id,String name) {
this.id = id;
this.name = name;
}
public String toString() {
return "【id:"+id+" name:"+name+"】";
}
}
class DoubleLinkedList{
private Node head = new Node(0,"");
public void addToEnd(Node node) {
Node temp = head;
while(temp.next!=null) {
temp = temp.next;
}
temp.next = node;
node.pre = temp;
}
public void delete(int i) {
Node temp = head.next;
while(temp.next!=null && temp.id != i) {
temp = temp.next;
}
if(temp.id == i) {
temp.pre.next = temp.next;
//如果删除的节点temp是最后一个节点,那么就不需要下面这一句话
if(temp.next!=null) {
temp.next.pre = temp.pre;
}
}
else {
System.out.println("链表中没有这个节点");
}
}
public void showList() {
Node temp = head.next;
while(temp!=null) {
System.out.println(temp);
temp = temp.next;
}
}
public void addByOrder(Node node) {
Node temp = head;
while(temp.next!=null &&temp.next.id < node.id) {
temp = temp.next;
}
if(temp.next != null ) {
temp.next.pre = node;
node.next = temp.next;
}
node.pre = temp;
temp.next = node;
}
}