簡單的單鏈表

/**
 * @Description 定義一個單鏈表
 * @auther Eleven
 * @create 2020-04-03 21:33
 **/
public class Node {
    //用於存儲鏈表裏面的數據
    int data;
    //用於存儲連接表中下一個node的地址
    Node next;

    //用於初始化的時候給node中保存數據
    public Node(int data) {
        this.data = data;
    }

    //鏈表添加元素的方法 (用於在鏈表後添加元素)
    public Node append(Node node){
        //定義變量接受當前節點
        Node currentNode = this;
        //循環查找
        while(true){
            //噹噹前節點的一下個節點爲空時,標示當前節點就是最後一個節點
            if (currentNode.next == null){
                //跳出循環
                break;
            }
            //噹噹前節點的下一個節點不爲空時,將下一個節點賦值給到當前節點
            currentNode = currentNode.next;
        }
        //跳出循環說明找到了最後一個節點,將新的節點添加到最後一個節點的後面
        currentNode.next=node;
        //將當前對象返回出去
        return this;
    }

    //刪除節點
    public void remove(Node node){
        //找到要刪除節點的下一個節點
        Node nextNode = node.next();
        //定義變量接受當前節點
        Node currentNode = this;
        //循環判斷當前節點的下一個節點是否等於要移除的節點,如果不等於就繼續循環,如果等於就跳出循環
        while(currentNode.next != node){
            //不等於就把當前的節點的下一個節點賦給當前節點
            currentNode = this.next;
        }
        currentNode.next = nextNode;
    }

    //添加鏈表中的節點 就是將當前節點的下一個節點指向該節點,原下一個節點改爲新增加的這個節點的下一個節點
    public void after(Node node){
        //定義變量接受當前節點
        Node currentNode = this;
        //獲取原先當前節點的下一個節點
        Node nextNext = currentNode.next;
        //當前節點的下一個節點設置爲新的節點
        this.next = node;
        //新節點的下一個節點設置爲原先節點的下一個節點
        node.next=nextNext;

    }

    //打印當前鏈表的數據
    public void print(){
        //定義變量接受當前節點
        Node currentNode = this;
        //如果當前節點不爲空,輸出當前節點的數據
        while(currentNode !=null ){
            //打印數據
            System.out.print(currentNode.getData());
            System.out.print(" ");
            //將當前節點的下一個節點賦值給到當前節點
            currentNode = currentNode.next;
        }
    }

    //獲取當前節點中的數據
    public int getData(){
        return this.data;
    }

    //獲取當前節點的下一個節點
    public Node next(){
        return this.next;
    }

    //判斷當前節點是否爲最後一個節點
    public boolean isLast(){
        return this.next==null;
    }
}

測試類

class Test{
    public static void main(String[] args) {
        Node n1 = new Node(1);
        Node n2 = new Node(2);
        Node n3 = new Node(3);
        n1.append(n2);
        n1.append(n3);
        n1.print();
       /* n1.remove(n1);
        n1.print();*/
        Node n5 = new Node(5);
        n2.after(n5);
        n1.print();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章