我@Stephen同意關於不給答案(全部),但我想我應該給你的提示。
一個重要的事情要明白的是,Java不顯式地指定指針 - 相反,每當非原語(例如,不char
,byte
,int
,double
,float
,long
,boolean
,short
)傳遞給函數,它作爲參考傳遞。所以,你可以使用臨時變量來交換值。嘗試自己編寫一個或看看下面:
public static void swapNodeNexts(final Node n1, final Node n2) {
final Node n1Next = n1.next;
final Node n2Next = n2.next;
n2.next = n1Next;
n1.next = n2Next;
}
然後你需要一個數據結構來保存Node
秒。重要的是隻有偶數的數字(奇數不必要地使事情複雜化)。還有必要初始化節點。你應該把它放在你的主要方法中。
public static final int NUMPAIRS = 3;
public static void main(final String[] args) {
final Node[] nodeList = new Node[NUMPAIRS * 2];
for (int i = 0; i < nodeList.length; i++) {
nodeList[i] = new Node();
nodeList[i].n = (i + 1) * 10;
// 10 20 30 40
}
// ...
}
重要的部分是設置節點的下一個值。你不能僅僅使用for
循環來循環所有這些循環,因爲最後一個的next
會拋出IndexOutOfBoundsException
。試着自己做一個,或者偷看我的。
for (int i = 0; i < nodeList.length - 1; i++) {
nodeList[i].next = nodeList[i + 1];
}
nodeList[nodeList.length - 1].next = nodeList[0];
然後對他們有for
循環運行的交換功能。但請記住,您不希望每節點上運行它......想一想。
如果你不能弄清楚,這是我的最終代碼:
// Node
class Node {
public int n; // value
public Node next; // pointer to next node
@Override
public String toString() {
return "Node [n=" + n + ", nextValue=" + next.n + "]";
}
}
// NodeMain
public class NodeMain {
public static final int NUMPAIRS = 3;
public static void main(final String[] args) {
final Node[] nodeList = new Node[NUMPAIRS * 2];
for (int i = 0; i < nodeList.length; i++) {
nodeList[i] = new Node();
nodeList[i].n = (i + 1) * 10;
// 10 20 30 40
}
for (int i = 0; i < nodeList.length - 1; i++) {
nodeList[i].next = nodeList[i + 1];
}
nodeList[nodeList.length - 1].next = nodeList[0];
// This makes 1 -> 2 -> 3 -> 4 -> 1 etc.
printNodes(nodeList);
for (int i = 0; i < nodeList.length; i += 2) {
swapNodeNexts(nodeList[i], nodeList[i + 1]);
}
// Now: 2 -> 1 -> 4 -> 3 -> 1 etc.
printNodes(nodeList);
}
private static void printNodes(final Node[] nodeList) {
for (int i = 0; i < nodeList.length; i++) {
System.out.println("Node " + (i + 1) + ": " + nodeList[i].n
+ "; next: " + nodeList[i].next.n);
}
System.out.println();
}
private static void swapNodeNexts(final Node n1, final Node n2) {
final Node n1Next = n1.next;
final Node n2Next = n2.next;
n2.next = n1Next;
n1.next = n2Next;
}
}
我希望你能找出至少一些這方面的指導。然而更重要的是,你理解這裏的概念很重要。如果您有任何問題,請發表評論。
你有什麼這麼遠嗎? :D –
這是一個面試問題,而不是作業?有趣。 – corsiKa
什麼是downvote?這是一個有效的問題,它也很有趣... upvoting。 – wchargin