一個簡單的Java單鏈表

一直對鏈表不太熟悉, 今天看了下並寫了下來, 錯的地方請指正.(注意:有的地方判斷不夠嚴格).

這是一個單向鏈表:

package com.test;
public class Link {
    
    Node root;
    
    private class Node{
        String name ;
        Node next;
        
        public Node(String name){
            this.name = name;
        }

        public void add(Node node) {
            if(this.next == null){
                this.next = node;
            }else{
                this.next.add(node);
            }
        }

        public void print() {
            System.out.print(this.name+"--->");
            if(this.next != null){
                this.next.print();
            }
        }

        public boolean query(String name) {
            if(this.next == null){
                return false;
            }else if(this.next.name.equals(name)){
                return true;
            }else{
                return this.next.query(name);
            }
        }

        public void delete(Node preNode , String name) {
            if(this.name.equals(name)){
                preNode.next = this.next;
            }else{
                this.next.delete(this , name);
            }
        }
    }
    
    public void addNode(String name){
        if(this.root == null){
            this.root = new Node(name);
        }else {
            this.root.add(new Node(name));
        }
    }
    
    public boolean queryNode(String name){
        if(this.root == null){
            return false;
        }else if(this.root.name.equals(name)){
            return true;
        }else{
            return this.root.query(name);
        }
    }
    
    public void deleteNode(String name){
        if(this.root != null){
            if(this.root.name.equals(name)){
                this.root = this.root.next;
            }else{
                this.root.next.delete(root,name);
            }
        }
    }
    
    public static void main(String[] args) {
        Link link = new Link();
        link.addNode("根");
        link.addNode("1");
        link.addNode("2");
        link.addNode("3");
        link.addNode("4");
        link.print();
        System.out.println("");
        System.out.println(link.queryNode("1"));
        System.out.println("");
        link.deleteNode("2");
        link.print();
    }
    
    void print(){
        if(this.root != null){
             this.root.print();
        }
    }

}

打印結果:

   根--->1--->2--->3--->4--->
   true
   根--->1--->3--->4--->

發佈了29 篇原創文章 · 獲贊 41 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章