JAVA:数据结构

JAVA:数据结构,第1张

public class Test {
    public static void main(String[] args) {
        HeroNode h1 = new HeroNode(1,"001","111");
        HeroNode h2 = new HeroNode(2,"002","222");
        HeroNode h3 = new HeroNode(3,"003","333");
        HeroNode h4 = new HeroNode(4,"004","444");

        HeroNode h_modify = new HeroNode(4,"andfk","afnbh");

        DoubleLinkedList d1 = new DoubleLinkedList();
        d1.add(h1);
        d1.add(h2);
        d1.add(h3);
        d1.add(h4);
        
        System.out.println(d1.head.next.name);
        System.out.println(d1.head.next.next.name);
        System.out.println(d1.head.next.next.next.name);
        System.out.println(d1.head.next.next.next.next.name);

    }
}
class HeroNode{
    int no;
    String name;
    String nickname;
    HeroNode pre;
    HeroNode next;
    public HeroNode(int no,String name,String nickname){
        this.no = no;
        this.name = name;
        this.nickname = nickname;
    }
}
class DoubleLinkedList{
    HeroNode head = new HeroNode(0,"头结点","Head");

    public void add(HeroNode h1){
        HeroNode temp = head;
        while(true){
            if(temp.next == null){
                break;
            }
            temp = temp.next;
        }
        temp.next = h1;
        h1.pre = temp;
    }

    public void delete(HeroNode h1){
        HeroNode temp = head;
        if(temp.next == null){
            System.out.println("链表为空,无法删除");
        }

        boolean flag = false;
        while(true){
            if(temp.no == h1.no){
                flag = true;
                break;
            }
            if(temp.next == null){
                break;
            }
            temp = temp.next;
        }

        if(flag){
            if(temp.next != null){
                temp.pre.next = temp.next;
                temp.pre = temp.next.pre;
            }else{
                temp.pre.next = null;

            }
        }else{
            System.out.println("没有找到要删除的节点");
        }
    }

    public void modify(HeroNode h_tobemodofy){
        HeroNode temp = head.next;
        boolean flag = false;

        if(head.next == null){
            System.out.println("链表为空,无法修改");
        }

        while(true){
            if(temp  == null){
                break;
            }
            if(temp.no == h_tobemodofy.no){
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if(flag){
            temp.name = h_tobemodofy.nickname;
            temp.nickname = h_tobemodofy.nickname;
        }else{
            System.out.printf("很抱歉,没有找到编号为%d的节点",h_tobemodofy.no);
        }
    }
}

经过测试,以上代码没什么问题,但我的问题是:怎么判断该把temp赋head还是赋head.next呢?

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/756667.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-30
下一篇 2022-04-30

发表评论

登录后才能评论

评论列表(0条)

保存