search
HomeJavajavaTutorialHow to implement addition, deletion and modification of doubly linked list in java

One-way linked list can only search in one direction, while doubly linked list can search forward or backward

One-way linked list cannot delete itself and needs to rely on auxiliary nodes, while doubly linked list can Self-delete

1. The traversal method is the same as that of a singly linked list, except that it can be searched forward or backward

2. Add (default is added to the end of a doubly linked list)

(1) First find the last node of the doubly linked list

(2) temp.next = newHeroNode

(3) newHeroNode.pre = temp

3. The modification idea is the same as the original one-way linked list

4. Deletion

(1) Because it is a two-way linked list, we can realize self-delete Node

(2) Directly find the node to be deleted, such as temp

(3) temp.pre.next = temp.next

(4) temp.next.pre = temp.pre

Code implementation

package com.hsy.linkedlist;

public class DoubleLinkedListDemo {

    public static void main(String[] args) {
        System.out.println("双向链表测试:");
        //先创建节点
        HeroNode2 hero1 = new HeroNode2(1, "刘备", "仁义");
        HeroNode2 hero2 = new HeroNode2(2, "关羽", "武圣");
        HeroNode2 hero3 = new HeroNode2(3, "张飞", "暴躁");
        HeroNode2 hero4 = new HeroNode2(4, "赵云", "单骑救主");

        //创建一个双向链表
        DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
        doubleLinkedList.add(hero1);
        doubleLinkedList.add(hero2);
        doubleLinkedList.add(hero3);
        doubleLinkedList.add(hero4);

        //显示链表
        doubleLinkedList.showList();

        //修改
        HeroNode2 newHeroNode = new HeroNode2(4, "好汤圆", "hsy");
        doubleLinkedList.update(newHeroNode);
        System.out.println("修改后:");
        doubleLinkedList.showList();

        //删除
        doubleLinkedList.delete(3);
        System.out.println("删除后:");
        doubleLinkedList.showList();
    }

}

//创建一个双向链表
class DoubleLinkedList {
    //初始化一个头节点,不存放数据
    private final HeroNode2 head = new HeroNode2(0, "", "");

    //返回头节点
    public HeroNode2 getHead() {
        return head;
    }

    //遍历
    public void showList() {
        //判断链表是否为空
        if (head.next == null) {
            System.out.println("链表为空!");
        }
        //由于头节点不能动,因此我们需要一个辅助变量来遍历
        HeroNode2 temp = head.next;
        while (true) {
            //判断链表是否到最后
            if (temp == null) {
                break;
            }
            System.out.println(temp);
            //这时需要将temp后移,否则会陷入死循环
            temp = temp.next;
        }
    }

    //添加一个新的节点在双向链表中
    public void add(HeroNode2 heroNode2) {
        //思路:(不考虑编号顺序)
        //1.找到当前链表的最后节点
        //2.将最后这个节点的next域指向新的节点
        HeroNode2 temp = head;
        //遍历链表,找到最后的节点
        while (true) {
            if (temp.next == null) {
                break;
            }
            //如果没有找到最后,将temp后移
            temp = temp.next;
        }
        //必须保证退出while循环时,temp指向链表的最后,并将最后这个节点的next域指向新的节点
        //形成一个双向链表
        temp.next = heroNode2;
        heroNode2.pre = temp;
    }

    //修改节点
    public void update(HeroNode2 newHeroNode2) {
        //判断链表是否为空
        if (head.next == null) {
            System.out.println("链表为空!");
        }
        HeroNode2 temp = head.next;
        boolean flag = false;
        while (true) {
            if (temp == null) {
                break;
            }
            if (temp.no == newHeroNode2.no) {
                //找到
                flag = true;
                break;
            }
            temp = temp.next;
        }
        //根据flag判断是否找到需要修改的值
        if (flag) {//编号已经存在
            temp.name = newHeroNode2.name;
            temp.nickname = newHeroNode2.nickname;
        } else {//没有找到
            System.out.println("没有找到编号为:" + newHeroNode2.no + "的节点,不能修改");
        }
    }

    //删除节点
    public void delete(int no) {
        //判断当前链表是否为空
        if (head.next==null){
            System.out.println("链表为空,无法删除");
        }
        HeroNode2 temp = head.next;
        boolean flag = false;
        while (true) {
            if (temp == null) {
                break;
            }
            if (temp.no == no) {
                //找到了待删除节点的前一个结点temp
                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("要删除的" + no + "节点不存在");
        }
    }
}

class HeroNode2 {
    public int no;
    public String name;
    public String nickname;
    public HeroNode2 next;//指向下一个节点
    public HeroNode2 pre;//指向上一个节点

    //创建构造器
    public HeroNode2(int no, String name, String nickname) {
        this.no = no;
        this.name = name;
        this.nickname = nickname;
    }

    @Override
    public String toString() {
        return "HeroNode{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", nickname='" + nickname + '\'' +
                '}';
    }
}

The above is the detailed content of How to implement addition, deletion and modification of doubly linked list in java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor