双向链表的增删改代码实现

定义节点:

class DoubleNode{
    int value;
    String name;
    DoubleNode next;
    DoubleNode pre;

    public DoubleNode(int value, String name) {
        this.value = value;
        this.name = name;
    }

    public DoubleNode(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "DoubleNode{" +
                "value=" + value +
                ", name='" + name + '\'' +
                '}';
    }
}

定义链表及操作:

class DoubleLinkedList{
    //头结点
    DoubleNode head = new DoubleNode(0);

    public DoubleNode getHead() {
        return head;
    }
    
    //尾插增加节点
    public void addLast(DoubleNode newNode){
        DoubleNode cur = head;
        while (cur.next != null){
            cur = cur.next;
        }
        cur.next = newNode;
        newNode.pre = cur;
    }
    //更新节点
    public void update(DoubleNode node){
        if (head.next == null){
            System.out.println("链表为空");
            return;
        }
        DoubleNode cur = head;
        while (cur != null){
            if (cur.value== node.value){
                cur.value = node.value;
                cur.name = node.name;
                break;
            }
            cur = cur.next;
        }
    }
    //删除节点
    public void deleteNode(DoubleNode node){
        if(head.next == null){
            System.out.println("链表为空");
            return;
        }
        DoubleNode cur = head;
        while (cur != null){
            if (cur == node){
                cur.pre.next = cur.next;
                if (cur.next != null) {
                    cur.next.pre = cur.pre;
                }
                break;
            }
            cur = cur.next;
        }
    }
    //打印链表
    public void printLinkedList(){
        if (head.next == null){
            System.out.println("链表为空");
        }
        DoubleNode cur = head.next;
        while (cur != null){
            System.out.println(cur);
            cur = cur.next;
        }
    }
}

代码测试:

public static void main(String[] args) {
        DoubleNode n1 = new DoubleNode(10,"孙悟空");
        DoubleNode n2 = new DoubleNode(20,"猪八戒");
        DoubleNode n3 = new DoubleNode(30,"吴迪");

        DoubleLinkedList linkedList = new DoubleLinkedList();
        linkedList.addLast(n1);
        linkedList.addLast(n2);
        linkedList.addLast(n3);

        System.out.println("更新前:");
        linkedList.printLinkedList();

        DoubleNode new1 = new DoubleNode(10,"芜湖起飞");
        linkedList.update(new1);
        System.out.println("更新后:");
        linkedList.printLinkedList();

        System.out.println("删除节点前:");
        linkedList.printLinkedList();

        linkedList.deleteNode(n2);
        System.out.println("删除节点后:");
        linkedList.printLinkedList();
    }

测试结果:

posted @ 2020-07-19 15:46  硬盘红了  阅读(186)  评论(0编辑  收藏  举报