0

I'm using a custom LinkedList class that goes like this:

public class LinkedList {
    // Get and Set methods are NOT necessary!

    private LinkedList next;    
    private final String word;

    public LinkedList(String word, LinkedList next) {
        this.word = word;
        this.next = next;
    }

Now my task is to write a method that takes an array of Strings, and coverts each string object into a LinkedList WITHOUT loops, so using recursion. How can this be done without loops? This is unimaginable to me. Where do I begin?

Edit: Let me clarify that the function I'm supposed to write only takes one argument, which is an array of Strings, and returns a LinkedList..

7
  • 1
    This sounds suspiciously like a homework question... Commented Nov 2, 2010 at 2:28
  • LinkedList(word[n],LinkList(word[n-1])); ? Make sure to check conditions so you do have any outofbounds errors. Commented Nov 2, 2010 at 2:28
  • @MrGumbe: What's wrong with that? Commented Nov 8, 2010 at 12:24
  • @Laurence: "the homework tag, like other so-called 'meta' tags, is now discouraged." Commented Nov 8, 2010 at 12:26
  • @Roger: that post makes the assertion that homework tag is a meta-tag with nothing to really back it up. The blog post it links to never mentions homework except in a question a commenter made. Commented Nov 8, 2010 at 20:25

8 Answers 8

2
enter code here
    public LinkedList arrayToLinkedList(String[] myArray)
{
        String[] toConvert = myArray;
        List<String> toConvertList = (List) Arrays.asList(toConvert);
        LinkedList<String> convertedLinkedList = new LinkedList<String>(toConvertList); 
        return convertedLinkedList;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Probably just me, but I don't like any of the solutions provided.

    /**
     * Creates linked list from array input.
     * 
     * @param input
     *            data array
     * @return linked list with data
     */
    public static LinkedList Of(String[] input) {
        // Checks if array has elements.
        if (input == null || input.length < 1)
            return null;
        // Starts creating the array using overload 2.
        return LinkedList.Of(input, 0);
    }

    /**
     * Creates linked list from array input (overload 2).
     * 
     * @param input
     *            data array
     * @param i
     *            counter to remember at what element is current
     * @return linked list with data
     */
    public static LinkedList Of(String[] input, int i) {
        //Tests if counter is within array elements. 
        if (input.length - 1 > i)
            // Returns new element with (current element data, reference
            // to next element). Note that next element will be returned
            // by this same method (this is why it is recursive).
            return new LinkedList(input[i], LinkedList.Of(input, i + 1));
        //Last element. From here backtracking will begin. 
        return new LinkedList(input[i], null);
    }

Here is something else:

    public String toString() {
        StringBuilder sb = new StringBuilder(this.word);
        LinkedList tmp = this;
        while (tmp.next != null) {
            sb.append(" > ");
            tmp = tmp.next;
            if (tmp.word != null)
                sb.append(tmp.word);
        }
        return sb.toString();
    }

And to test:

    String str = "Neque porro quisquam est qui dolorem ipsum quia "
            + "dolor sit amet, consectetur, adipisci velit...";
    LinkedList ll = LinkedList.Of(str.split("\\s+"));
    System.out.println(ll);

6 Comments

Yes :D (you forgot to mention how the elements should be put in).
Ya that works..so is there anyway this can be done without that second method?
Not efficiently, because you do not want to resize the array.
Actually you could also do it if you would create a static counter, but that is just bad style.
Well I was hoping to learn something, but Im not understanding how your code works. Any chance you can comment it and I will mark you right answer?
|
1

I'm not sure what language you are using, but here's a general idea:

public LinkedList myfunction(String arr[]) {
    if(arr.empty == true)
        return void;

    //return the array minus the first element
    String shorterarray[] = substr(arr[],1);

    //recursively create the next element
    LinkedList myItem = new LinkedList(arr[0], myfunction(shorterarray[]));
}

You'll have to do the subtring and boundary checking in whatever language you are using.

Comments

1

How about:

public static void main(String[] args) {
    String[] data = new String[] { "1", "2", "3" };

    LinkedList head = build(data);
    while (head != null) {
        System.out.println(head.word);
        head = head.next;
    }
}

private static LinkedList build(String[] data) {
    if (data == null || data.length == 0) {
        return null;
    }

    LinkedList head = new LinkedList(data[0], null);
    build(head, data, 1);
    return head;
}

private static LinkedList build(LinkedList node, String[] data, int index) {
    if (index == data.length) {
        return node;
    }

    node.next = build(new LinkedList(data[index], null), data, ++index);
    return node;
}

private static class LinkedList {
    private final String word;
    private LinkedList next;    

    public LinkedList(String word, LinkedList next) {
        this.word = word;
        this.next = next;
    }
}

To add, it might also be worth while pointing out that creating collections with recursion is really bad in practice - it can easily blow out your stack size.

3 Comments

While that works... you might not want to give someone the whole answer for a question tagged as homework. :-)
sorry, i had no idea there were rules or understandings about answering these types of questions.
Not like I understood anything in that code :/ I'm supposed to write a function that only takes an array of strings as an arguement
1

First, anything you can do with iteration (looping) you can do with recursion, and vice-versa (though without tail-call elimination, something Java doesn't have, recursion is often more expensive than iteration).

When trying to figure out how to solve a problem recursively you want to figure out how to break off one or more pieces of the problem that look like the same sort of problem but only smaller. With list problems that often means that when given an n element list you want to recursively handle n-1 elements. You also need to have a base case so the recursion will terminate. With lists the base case is usually a list of 0 elements.

An array is a lot like a list, but Java arrays don't have slicing (ie: you can't pass around just a piece of an array) so you'll want a helper method that knows which piece of the array we care about:

private static LinkedList fromArray(String[] a, int offset) {

Since your LinkedList class breaks down into a word and then the tail part of the list (pointed to by next) it makes sense for us to also deal with the tail part of the input array. The offset parameter lets us know how much of the tail part of the array we'll be looking at: it's the first index we care about.

The public method will just call the helper method giving it an offset of 0:

public static LinkedList fromArray(String[] a) {
    return fromArray(a, 0);
}

An offset of 0 means we care about element 0 (the first element) and every element after it.

So now to write the "helper" method, which is where all of the real work is done.

First, get the base case out of the way. The base case is where the part of the array we're converting is empty. That would be the case if offset >= a.length. In that case we want to return an empty LinkedList, which is actually represented by null. So return null in that case.

Once the base case is taken care of, think about the recursive case. We have one or more elements in the part of the array we care about. Let's create a LinkedList to hold the first of those elements, a[offset]. (The first element we care about, that is. Recall that the helper only cares about the part of the array starting at offset up to the end.) The rest of the elements can be handled by calling ourselves passing in the same array, but incrementing offset by one, as we don't want the recursive call to handle the element we already handled.

Comments

0

Call a function that takes three arguments; a source array, a current position in the array, and a destination linked list.

Does that get your head going/can you figure it out from there?

Comments

0

Try this:

private LinkedList formlist(LinkedList list, String[] str, int length, int i) {
    if(i==length)
        return list;
    return formlist(new LinkedList (str[i],list),str,length,i+1);

}

4 Comments

but my method is only supposed to take one argument, which is an array of strings..
are you limited to a single method or even some language?
Yes only a single method and its Java
But I cannot create my own method I have to use what I am given
0

Ok, since there is the requirement for a single method with String[] args. here is a java example. (based on a previous answer but converted to java)

private LinkedList build(String arr[]) {
    if(arr.length == 0)
        return null;

    //return the array minus the first element
    String shorterarray[] = Arrays.copyOfRange(arr, 1, arr.length);

    //recursively create the next element
    return new LinkedList(arr[0], build(shorterarray));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.