java 模拟一个单向链表

class Node 
{
    //当前节点
    private String data;
    //下个节点
    private Node next;
    
    //当前节点
    public void setData(String data){
        this.data=data;
    }
    public String getData(){
        return this.data;
    }
    
    //下个节点
    public void setNext(Node next){
        this.next=next;
    }
    public Node getNext(){
        return this.next;
    }
}

public class MyLink
{
    public static void main(String args[]){

        //第一个节点
        Node node1 = new Node();
        node1.setData("A");
        
        //第二个节点
        Node node2 = new Node();
        node2.setData("B");
        
        //第三个节点
        Node node3 = new Node();
        node3.setData("C");
        
        //第四个节点
        Node node4 = new Node();
        node4.setData("D");
        
        //设置第一个节点的下个节点
        node1.setNext(node2);
        
        //设置第二个节点的下个节点
        node2.setNext(node3);
        
        //设置第三个节点的下个节点
        node3.setNext(node4);
       
        //输出所有节点
        printNode(node1);

    }

    
    public static void printNode(Node node){
        
        //输出当前节点信息
        System.out.print(node.getData()+"-->");

        //假如当前节点还有子节点
        if(node.getNext()!=null){
            printNode(node.getNext());//调用方法本身,传入子节点
        }else{
            System.out.print("null");
        }
        
    }
    
}

 执行结果为:

A-->B-->C-->D-->null

猜你喜欢

转载自www.cnblogs.com/hellowzd/p/9717763.html
今日推荐