aspose file tools*
The moose likes Beginning Java and the fly likes moving a linked list into an array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "moving a linked list into an array" Watch "moving a linked list into an array" New topic
Author

moving a linked list into an array

James Novak
Greenhorn

Joined: Sep 16, 2009
Posts: 10
Hi I'm working on this new linked list program. Basically what I wanted to do was move all of the data from the linked list into an array, then have the array print out backwards. I was wondering how I would do that. Some one suggested using a loop to me to do that, but I find that method confusing still



This part below that creates the ListNode elements.


This is the driver.



David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Well, you're already looping over the list--the next part is moving each element to an array. What have you tried so far?
James Novak
Greenhorn

Joined: Sep 16, 2009
Posts: 10
In all honesty I've just tried doing research because I have no clue as to how to really approach the problem.
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

I'd approach the problem by making an array and as I iterate over the linked list put each list item into the array.

Do you know how to declare an array?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18837
    
  40

To be honest, this seems to be less of a linked list, and more like, some code that manipulate a bunch of nodes that happen to be linked together.

Maybe it would be a good idea to implement the linked list first. Have instances of your linked list class maintain the head, tail, and other needed data. Have methods that can be called to add, insert, and remove elements -- these methods should not expose the node class. Or maybe implement an iterator.

Once you have a fully functioning linked list class, creating a "to array" method should be straightforward.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
James Novak
Greenhorn

Joined: Sep 16, 2009
Posts: 10


This is what I have so far. I figure that I still need the cursor part of the program and I probably need to make it an array. What should I do from here?

NOTE: Am I accidentally making the entire linked list one item in the array?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38851
    
  23
No. You are accidentally making a 1-element array which you promptly discard.
James Novak
Greenhorn

Joined: Sep 16, 2009
Posts: 10
Well how can I change my code to take all of the numbers and turn them into multiple elements.
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Create an array of the correct size, and save each list element in successive array elements.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: moving a linked list into an array