开发者社区> 问答> 正文

求单链表的长度的递归算法(java)

求单链表的长度的递归算法(java)

展开
收起
知与谁同 2018-07-22 17:23:21 2797 0
1 条回答
写回答
取消 提交回答
  • package cn.uestc.fz;

    class Node{
    int data;
    Node next;
    public Node(int data,Node next){
    this.data=data;
    this.next=next;
    }
    }
    public class LinkedList {
    Node head;
    public void add(Node node){
    if(head==null)
    head=node;
    else{
    Node p=head;
    while(p.next!=null)
    p=p.next;
    p.next=node;
    }
    }

    public int length(){
    return this.length(head);
    }

    public int length(Node node){
    if(node==null)
    return 0;
    else if(node.next==null)
    return 1;
    else
    return 1+this.length(node.next);
    }

    public void printList(){
    Node p=head;
    while(p!=null){
    System.out.print(p.data+"->");
    p=p.next;
    }
    System.out.println();
    }

    public static void main(String args[]){
    LinkedList list = new LinkedList();
    list.add(new Node(1,null));
    list.add(new Node(2,null));
    list.add(new Node(3,null));
    list.add(new Node(4,null));
    list.add(new Node(5,null));
    list.add(new Node(6,null));
    list.printList();
    System.out.println(list.length());
    }
    }

    刚写的。
    2019-07-17 22:54:52
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载