用Java和C++均可,向高手求教!Java最好,因为我对Java更熟悉一点

解决方案 »

  1.   

    链表的长度需要递归?
    没有听说过,一般就是保存一个int值表示链表的长度,或者是遍历一次链表就知道长度了。不需要递归吧
      

  2.   

    如果是不带头结点的:public int length(LNode ln){
       if(ln==null){
          return 0;
       }
       return 1+length(ln.getNext());
    }
      

  3.   

    public class Test {    public static void main(String[] args) {
            ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, null))));
            int length = ListNode.getLength(head, 0);
            System.out.println(length);
        }
    }class ListNode {    private int value;
        private ListNode next;    public ListNode(int value, ListNode next) {
            this.value = value;
            this.next = next;
        }    public ListNode getNext() {
            return next;
        }    public int getValue() {
            return value;
        }    public static int getLength(ListNode head, int length) {
            if (head == null) {
                return length;
            }
            return getLength(head.next, length + 1);
        }
    }
      

  4.   

    求长度 我更喜欢循环:public static int getLength(ListNode head, int length) {
        if (head != null) {
         length ++;
        
         while(head.getNext()!= null){
             head = head.getNext();
                length ++;
         }
        }
        return length;
    }