【java數據結構】利用java實現一個簡單的鏈表結構

定義:java

所謂鏈表就是指在某節點存儲數據的過程當中還要有一個屬性用來指向下一個鏈表節點,這樣的數據存儲方式叫作鏈表node

鏈表優缺點:學習

優勢:易於存儲和刪除測試

缺點:查詢起來較麻煩this

下面咱們用java來實現以下鏈表結構:spa


首先定義節點類:code

package LinkTest;
/**
 * 鏈表節點類
 * @author admin
 *
 */
public class Node {
    private int value;//存儲數據
    private Node next;//下一個節點
    /**
     * 定義構造器
     * @param vlaue
     * @param value 
     */
    public Node(int value){
        this.value=value;
    }
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public Node getNext() {
        return next;
    }
    public void setNext(Node next) {
        this.next = next;
    }
}


而後定義一個鏈表類:遞歸

* 注意:遍歷鏈表定義了兩個方法,一個是普通方法,一個是遞歸方法,均可以遍歷出來
get

package LinkTest;
/**
 * 鏈表
 * @author admin
 *
 */
public class Link {
    private Node current;
    private Node root;
    public void insert(int vlaue){
        Node newNode=new Node(vlaue);
        if(this.current==null){
            this.current=newNode;
            this.root=this.current;
        }else{
            this.current.setNext(newNode);
            this.current=this.current.getNext();
        }
    }
    //普通遍歷
    public void getList(){
        this.current=this.root;
        while(this.current!=null){
            System.out.print(this.current.getValue());
            this.current=this.current.getNext();
            if(this.current!=null){
                System.out.print("------->");
            }
        }
    }

    //遞歸遍歷
    public void getList2(){
        DG(this.root);
    }

    //遞歸方法
    public void DG(Node node){
        System.out.print(node.getValue()+"----->");
        if(node.getNext()!=null){
            DG(node.getNext());
        }else{
            return;
        }
    }
}


測試類:class

package LinkTest;
/**
 * 測試類
 * @author admin
 *
 */
public class Test {
    public static void main(String[] args){
        Link l=new Link();
        l.insert(1);
        l.insert(4);
        l.insert(5);
        l.insert(6);
        l.insert(9);
        l.insert(8);
        l.getList();
    }
}

測試類運行結果:

1------->4------->5------->6------->9------->8


這樣咱們就用java實現了一個簡單的鏈表結構,以爲哪裏有問題歡迎在評論區指正,相互學習,若是以爲不錯就贊一個吧

謝謝您的閱讀!

相關文章
相關標籤/搜索