问题
The problem is to find nth element in a linked list, i have the problem figured out on finding the element.
But i have to read an input from a file and output the nth element from the list
For example
Input would look like this
a b c d 4
e f g h 2
Output would like
a
g
It is stated "The first argument will be a path to a filename containing a series of space delimited characters followed by an integer representing a index into the list (1 based), one per line"
I am not sure how i would go about this? Would i first the read the file and store each line in a List?
回答1:
Yes, you should read the file line by line, and store each line in a List<String>.
Then, simply do this:
String line; // use an iterator on the list to get each line
String[] elements = line.trim().split("\\s");
char[] chars = new char[elements.length - 1];
int index = Integer.parseInt(elements[elements.length - 1]);
for (i = 0; i < elements.length - 1; i++)
char[i] = elements[i].charAt(0);
Now you have the characters in an array ... and you said you already have the rest figured out.
来源:https://stackoverflow.com/questions/21591522/input-from-a-file-find-the-nth-element-for-the-linked-list