递归toString方法

时间:2013-06-02 20:58:15

标签: java recursion

我正在处理我当前的任务,即创建一个LinkedList数据结构,我已经创建了它以及其他方法,它完全正常。我的最后一个问题是制作一个toString方法。应该是:

“toString方法返回列表的String表示。用逗号分隔每个项目,并将项目括在大括号中,例如{1,4,7,5}。公共toString方法必须调用私有,递归生成以逗号分隔的项目列表的方法。(您可以在公共方法中添加大括号。)“

我的公共toString方法正常工作;

    public String toString() {
    int size = getSize();
    String str = "{ ";
    Link current = first;

    for(int i = 0; i < getSize(); i++, current = current.next) {
        str += current.getiData() + " ";
    }

    str += " }";
    return str;
}

(我知道我应该使用StringBuilder,只是临时使用+ =。)然而对于私有方法我甚至很困惑甚至写它。现在,我能想到这样做的唯一方法是:

private String toString(int x) {
    if(i > 0) {
        toString(--x);
    }
    return ", ";
}

哪个只是愚蠢(实际上不是递归),任何人都可以澄清要做什么,和/或给出伪代码吗?

3 个答案:

答案 0 :(得分:5)

你想要这样的东西(给出递归的基本思想,不起作用)

privat String toString(Link link) {
  if (link.isLast()) {
    return link.value();
  }
  else {
    return link.value() + toString(link.next());
  }
}

答案 1 :(得分:4)

我认为其他答案从代码的角度来看是合适的,但我只想添加一些理论来帮助您了解如何实现目标。在进行递归时,您总是需要两件事:基本案例和递归案例。基本案例非常简单易于解决,递归案例是您如何解决可解决的简单案例。

链接列表本身就是一种递归数据结构。例如,如果您有一个包含10个项目的链接列表,则可以将其作为单个节点进行图片处理,并附加9个项目的链接列表。

因此对于基本情况(再次借用@Chris的答案),执行toString()的最简单列表是一个空列表。所以你的基本情况看起来像这样(伪代码):

if(list is empty)
{
   return "";
}

然后,您的递归案例需要使用现有的链接列表并尝试向下工作。最简单的方法是中断您知道可以解决的一小部分问题,解决问题,然后解决您留下的稍微小一点的问题。在打印链接列表的情况下,这意味着您只需从列表中抓取一个项目,将其转换为字符串,然后担心列表的其余部分。所以你的递归情况会看起来像这样(伪代码):

if(list is not empty)
{
   String x = take the current node and translate it to a string;

   Add x to your running value of the String value of the entire list

   Recursively call this function with the next node in the list
   (you reduce your list size by 1 with each call and work down to your base case of an empty list)
}

希望这有助于您了解如何针对此问题递归地找到解决方案。如何让它发挥作用肯定有很多变化;没有一种“正确”的方式可以递归地进行,就像没有一种“正确”的方式来编写循环一样,但一般的“基本情况”和“递归情况”思维模型通常是最好的起点。

答案 2 :(得分:1)

这有点奇怪,因为toString方法的签名没有参数,这意味着需要另一种方法。在链表中,每个节点都有datapointer到下一个节点。

public String getData(Node n, String value)
{
     if(n == null)
     {
         // We know we're at the end, so don't proceed.
         return value;
     }
     else
     {
         // n isn't empty, and ignoring the lack of stringbuilder
         value += n.getData();
         // Make a recursive call with the next value in the list, and the new string.
         return getData(n.next(), value);
     }
}
相关问题