链表

Java实现单向链表

package com.arenas.datastruct;

public class Linked {

    class Node{
        private String name;
        private Node next;
        
        public Node (String name){
            this.name = name;
        }
        
        public void add (Node node){
            if (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 search (String name){
            if (this.name.equals(name))
                return true;
            else {
                if (this.next == null)
                    return false;
                else 
                    return this.next.search(name);
            }
        }
        
        public void delete(String name){
            if (this.next.name.equals(name))
                this.next = this.next.next;
            else
                this.next.delete(name);
        }
    }

    private Node root;
    
    public void add (String name){
        Node node = new Node(name);
        if (root == null)
            root = node;
        else
            root.add(node);
    }
    
    public void print(){
        if(root != null)
            this.root.print();
    }
    
    public boolean search(String name){
        if (root != null)
            return root.search(name);
        else
            return false;
    }
    
    public void delete(String name){
        if (this.search(name)){
            if (this.root.name.equals(name)){
                if( this.root.next != null)
                    this.root = this.root.next;
                else
                    this.root = null;
            }else{
                this.root.delete(name);
            }
        }
    }
    
    public static void main(String[] args) {
        Linked link = new Linked();
        link.add("kobe");
        link.add("tracy");
        link.add("kevin");
        link.add("kid");
        link.add("durant");
        
        link.print();
        System.out.println();
        link.delete("kobe");
        System.out.println(link.search("kobe"));
        link.delete("durant");
        link.print();
    }

}

kobe->tracy->kevin->kid->durant->
false
tracy->kevin->kid->

posted @ 2016-10-23 16:42  Steve_Nash  阅读(147)  评论(0编辑  收藏  举报