Java關於鏈表的增加、刪除、獲取長度、打印數值的實現


package com.shb.java;

public class Demo8 {
    public Node headNode = null;
    /**
     * @param args
     * @date 2016-9-28
     * @author shaobn
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Demo8 linkedList = new Demo8();
        linkedList.addNode(1);
        linkedList.addNode(2);
        linkedList.addNode(34);
        linkedList.addNode(14);
//        System.out.println(linkedList.getLength());
        linkedList.deleteNode(1);
        linkedList.printNode();
    }
    /**
     * 插入到鏈表中
     * @param data
     * @date 2016-9-28
     * @author shaobn
     */
    public void addNode(int data){
        Node node = new Node(data);
        if(headNode==null){
            headNode = node;
            return;
        }
        Node tmpNode = headNode;
        if(tmpNode.next==null){
            tmpNode.next = node;
            return;
        }
        while(tmpNode.next!=null){
            tmpNode = tmpNode.next;
        }
        tmpNode.next = node;
    }
    /**
     * 打印節點的值
     * 
     * @date 2016-9-28
     * @author shaobn
     */
    public void printNode(){
        Node tmpNode = headNode;
        while(tmpNode!=null){
            System.out.println(tmpNode.data);
            tmpNode = tmpNode.next;
        }
    }
    /**
     * 刪除節點
     * 
     * @date 2016-9-28
     * @author shaobn
     */
    public void deleteNode(int index){
        if(index<=0||index>this.getLength()){
            throw new RuntimeException("索引選取不合適");
        }
        int count = 1;
        Node tmpNode = headNode;
        while(tmpNode.next!=null){
            count++;
            if(index==1){
                headNode = tmpNode.next;
                break;
            }
            if(count==index){
                tmpNode.next = tmpNode.next.next;                
            }
            tmpNode = tmpNode.next;
            continue;
        }
        
        
        
    }
    /**
     * 獲得本鏈表的長度
     * @return
     * @date 2016-9-28
     * @author shaobn
     */
    public int getLength(){
        int length = 0;
        Node tmpNode = this.headNode;
        while(tmpNode!=null){
            length++;
            tmpNode = tmpNode.next;
        }
        return length;
        
    }
}
/**
 * 節點的類
 * @author shaobn
 * @date 2016-9-28
 * @package_name com.shb.java
 */
class Node{
    public int data;
    public Node next;
    public Node(int data){
        this.data = data;
    }
    
    
    
}

 


免責聲明!

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



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