求单链表的长度的递归算法(java)
收起
知与谁同
2018-07-22 17:23:21
2820
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