JAVA的單鏈表創建


有一說一 ,C的單鏈表創建(頭插,尾插)思路蠻簡單的,現在用JAVA寫感覺也還行?雖然沒有指針,但是代碼看起來更加簡單了

package linklist;

public class Node {
    Node next =null;
    int data;
    public Node(int data) {
        this.data=data;
    }

}
package linklist;

public class SingleLinkedList {
    Node head=null;
    
    //鏈表頭添加
    public void addHead(int data) {
        Node node = new Node(data);
        node.next =head;
        head =node;
    }
    //打印
    public void printLink() {
        Node curNode = head;
        while(curNode !=null) {
            System.out.println(curNode.data+" ");
            curNode = curNode.next;
        }
        System.out.println();
    }
    //長度
    public int length() {
        int length =0;
        Node curr = head;
        while(curr!=null) {
            length++;
            curr=curr.next;
        }
        return length;
    }
    
    //在尾部插入
    public void addLast(int data) {
        Node node = new Node(data);
        if(head==null) {
            head = node;
        }
        else {
            Node temp =head;
            while(temp.next!=null) {
                temp =temp.next;
            }
            temp.next=node;
        }
        
    }
    //按索引插入
    public void insertByIndex(int index,int data) {
        Node node = new Node(data);
        if(index<0||index>length()) {
            System.out.println("插入位置不對");
            return ;
        }
        int length=1;
        Node tmp = head;
        while(tmp.next!=null) {
            length++;
            tmp=tmp.next;
            if(index== length) {
                node.next=tmp.next;
                tmp.next=node;
                return;
            }
        }
    }
    //按索引刪除
    public void deleteByIndex(int index) {
        Node temp = head;
        if(index<0||index>length()) {
            System.out.println("位置不對");
            return;
        }else if(index ==0) {
            head=head.next;
        }
        else {
            for(int i=1;i<index;i++) {
                temp=temp.next;
            }
            temp.next=temp.next.next;
        }
    }
    

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SingleLinkedList list = new SingleLinkedList();
        
        list.addLast(1);
        list.addLast(3);
        list.addLast(4);
        list.printLink();
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM