無頭單鏈表的基本操作(Java)

鏈表

鏈表是一種物理存儲結構上非連續存儲結構,數據元素的邏輯順序是通過鏈表中的引用鏈接次序實現的

其實呢,鏈表的結構非常多樣,分爲以下情況

  • 單向 雙向
  • 無頭 有頭
  • 循環 非循環

這次呢,先說無頭單向非循環鏈表
在這裏插入圖片描述
鏈表的實現:

//結點類
class ListNode{
    public int data;
    public ListNode next;

    public ListNode(int data){
        this.data=data;
        this.next=null;
    }
}
//單鏈表類
public class MySignalList {
    public ListNode head;//head是引用
    //構造方法
    public MySignalList(){
        this.head=null;
    }
    //頭插
    public void addFirst(int data){
        ListNode node=new ListNode(data);//創建一個結點,node代表當前對象引用
        //如果鏈表爲空
        if (this.head==null){
            this.head=node;
        } else{
            node.next=this.head;
            this.head=node;
        }
    }
    //尾插
    public void addLast(int data){
        ListNode node=new ListNode(data);
        //鏈表爲空
        if (this.head==null){
           this.head=node;
        } else {
            ListNode cur=this.head;
            while(cur.next!=null){
                cur=cur.next;
            }
            cur.next=node;
        }
    }
    private ListNode searchIndex(int index){
        ListNode cur=head;
        while (index-1>0){
            cur=cur.next;
            index--;
        }
        return cur;
    }
    //任意位置插入,第一個數據節點爲0號下標
    public boolean addIndex(int index,int data){
        if (index<0||index>size()){
            System.out.println("位置不合法!");
            return false;
        }
        if (index==0){
            addFirst(data);
            return true;
        }
        else {
            ListNode cur = searchIndex(index);
            ListNode node=new ListNode(data);
            node.next=cur.next;
            cur.next=node;
            return true;
        }
    }
    //判斷是否包含一個key
    public boolean contains(int key){
        ListNode cur=this.head;
        if (cur==null){
            System.out.println("鏈表爲空!");
        }
        while (cur!=null){
            if (cur.data==key){
                return true;
            }
            cur=cur.next;
        }
        return false;
    }
    //鏈表的長度
    public int size(){
        ListNode cur=head;
        int count=0;
        if (cur==null){
            return 0;
        }
        else {
            while(cur!=null){
                count++;
                cur=cur.next;
            }
            return count;
        }
    }
    //打印單鏈表
    public void display(){
        ListNode cur=this.head;
        while(cur!=null){
            System.out.println(cur.data);
            cur=cur.next;
        }
    }
}

  • 頭插法
    在這裏插入圖片描述
  • 尾插法
    在這裏插入圖片描述
  • 任意位置插入
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章