如何递归获取链表的大小?

时间:2020-03-11 01:01:41

标签: java recursion linked-list

我正在尝试使用递归算法查找链表的大小。这是我到目前为止的内容:

  public int getCurrentSize()
  {
     int size = 0;

     size = getCurrentSizeHelper(headRef);

     return size;
  }


  public int getCurrentSizeHelper(BoxClass workingRef)
  {
     int sizeAtIndex = 0;

     //If empty, size is zero
     if (isEmpty())
        {
           return sizeAtIndex;
        }

     //If there is no next box, end recursion and increment size
     if (workingRef.nextRef == null)
        {
           sizeAtIndex++;
        }

     //While there are next boxes, increment size and continue recursion
     else
        {
           sizeAtIndex = getCurrentSizeHelper(workingRef.nextRef) + 1;
        }

     return sizeAtIndex;
  }

我早些时候工作过,但是,每次尝试运行它时,都会出现堆栈溢出错误。希望对这个问题有任何见识。

1 个答案:

答案 0 :(得分:1)

更好的紧凑版本(伪代码):

  public int getCurrentSizeHelper(BoxClass workingRef)
  {
       if (workingRef.isEmpty())
       {
           return 0;
       }
       return getCurrentSizeHelper(workingRef.nextRef) + 1;
  }

这将完成工作。举个例子,解决一下并检查一下自己。

相关问题