返回链表中奇数元素的字符串

时间:2013-11-18 14:08:46

标签: java linked-list tostring

我需要编写一个方法 - 返回一个带有奇数元素的字符串'toStrings与之间的冒号连接。换句话说,第1,第3,第5 ......元素。

我已经写了一个方法来返回所有元素的字符串:

public String toString (Node<E> node) {
    if (node == null) {
        return "";
    }
    else {
        Node<E> next = node.next ();
        return node.element () + (next == null ? "" : "\n") + toString (next);
    }
}
//Return String with all elements
public String toString() {
    return toString(head);
}

此代码尚未经过测试..

这是我第一次使用链接列表,所以我不确定是否有一个简单的单行程来完成这个或我需要使用的逻辑是什么?

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

为了正常工作,您应该稍微更改一下代码:

public String toString (Node<E> node) {
    if (node == null) {
        return "";
    }
    else {
        Node<E> next = node.next ();
        if(next == null){
           return node.element().toString(); //avoid null pointer exceptions
        }

        return node.element () + "\n" + toString(next.next());//continue recursion with an odd element
    }
}

此代码可以改进。

答案 1 :(得分:0)

为了获取链表中的所有其他元素,我会使用带有计数器的while循环来跟踪我们所在的元素,因此只有正确的元素被添加到字符串中。由于偶数可以很容易地用number % 2 == 0表示,奇数用number % 2 == 1来表示,只要计数器是最新的,就可以弄清楚当前节点是偶数还是奇数。

在此示例中,循环必须遍历列表中的每个节点,并且仅在计数器为偶数时才添加到字符串(如果要将其更改为奇数,则为奇数)。

public String toString(Node<E> node) {
    if (node == null) {
        return "";
    }

    String elements = ""; // I would recommend looking into StringBuilder
    int counter = 0;

    // add the first element to the string right away.
    // this will eliminate accidentally putting a \n at the beginning
    // of the string, before any elements have been added to it
    elements = node.element; // if you want odd elements instead of 
    node = node.next();      // even, swap these two lines.
    counter++;

    while (node != null) {
        if (counter % 2 == 0) { // only add the even elements
                                // this can easily be changed for odd elements
            elements = elements + "\n" + node.element;
        }
        node = node.next(); // go to the next node every iteration of the loop
        counter++; // always increment the counter
    }

    return elements;
}