使用java实现正向链表

Node类

public class Node {
    
    public Object data;
    public Node next;
    
    public Node(Object data) {
        super();
        this.data = data;
    }

NodeLink类

public class NodeLink {
    
    Node head;
    
    Node last;
    
    public void getLastNode(Node node){
        if(node.next!=null){
            getLastNode(node.next);
        }else if(node.next==null){
            last=node;
        }
    }
    
    public Node addNode(Node another){
        if(head==null){
            head=another;
        }else{
            getLastNode(head);
            System.out.println(last.data);
            last.next=another;
        }
        return head;
    }
    
    public void print(Node node){
        System.out.print(node.data+"-->");
        if(node.next!=null){
            this.print(node.next);
        }
    }

加几个方法就能变成双向链表
PS. 和机构,菜单的递归几乎一样
测试

public static void main(String[] args) {
        NodeLink link=new NodeLink();
        Node a=new Node("a");
        Node b=new Node("b");
        Node c=new Node("c");
        Node d=new Node("d");
        link.addNode(a);
        link.addNode(b);
        link.addNode(c);
        System.out.println();
//        System.out.println(a.next);
//        System.out.println(b.next);
//        System.out.println(c.next);
        link.addNode(d);
        System.out.println("-------------");
        link.print(link.head);
    }

张泽
5 声望1 粉丝