编辑代码

class Main {
	public static void main(String[] args) {
        
	}
}

//双向链表的功能
class DoubleLinkedList{
    private Node head = new Node(0,"");

    public Node getNode(){
        return head;
    }

    //遍历一个双向链表的方法
    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 add(Node node){
        Node temp = head;
        while(temp.next != null){
            temp = temp.next;
        }
        temp.next = node;//链接旧节点的下一个新节点
        node.pre = temp;//链接新节点的前一个节点
    }

    //修改一个节点的内容,和原来的单向链表一样
    public void update(Node node){
        if(head.next == null){
            System.out.println("链表为空");
            return;
        }
        //找到需要修改的节点,根据no编号
        //定义一个辅助变量
        Node temp = head.next;
        while(temp != null){
            if(temp.no == node.no){
                temp.name = node.name;
                System.out.println("修改成功");
                return;
            }
            temp = temp.next;
        }
        System.out.println("修改失败");
    }

    //删除节点,我们可以直接找到要删除的这个节点
    //找到后自我删除
    public void del(int no){
        if(head.next == null){
            System.out.println("链表为空");
            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){//如果删除的不是最后一个节点,就需要执行pre指针的赋值
                temp.next.pre = temp.pre;
            }
        }else{
            System.out.printf("要删除的 %d 节点不存在\n",no);
        }
    }

}

//双向链表的一个节点对象
class Node{
    public int no;
    public String name;
    public Node next;
    public Node pre;

    public Node(int no,String name){
        this.no = no;
        this.name = name;
    }

    @Override
    public String toString(){
        return "Node[no=" + no + ",name=" + name + "]";
    }
}