也許只是我,但我不喜歡任何提供的解決方案。
public static LinkedList Of(String[] input) {
if (input == null || input.length < 1)
return null;
return LinkedList.Of(input, input.length - 1);
}
public static LinkedList Of(String[] input, int i) {
if (i > 0)
return new LinkedList(input[i], LinkedList.Of(input, i - 1));
return new LinkedList(input[i], null);
}
下投票是可怕的,所以這裏是它的正確順序:
/**
* 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);
}
這是後話了投票:
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();
}
,並測試:
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);
這聽起來像一個功課問題... – cortijon 2010-11-02 02:28:13
LinkedList(word [n],LinkList(word [n-1])); ?確保檢查條件,以確保有任何outofbounds錯誤。 – Jim 2010-11-02 02:28:52
@MrGumbe:那有什麼不對? – 2010-11-08 12:24:47