になります。私が大学でこれをしたとき、2つのノードを交換するために、交換したい最初のノードの前にあるノードをつかみたい。例えば。あなたがここに
----> currNode -> node_A -> node_B -> node_C ------>
を持っている場合我々はnode_B
にcurrNode.next
を設定する必要がありますので、私たちはcurrNode
で停止node_A
node_B
と交換することを望みます。これに続いて
は、我々は(私はそれはいくつかのメソッドに渡されるだろうと仮定しています)、次います
Node tmp = curr;
Node A = curr.next;
Node B = curr.next.next;
Node C = curr.next.next.next;
は今、私たちは物事を正しく設定する必要があります。
今
tmp.setNext(B); //Now we have ----> tmp -> B
B.setNext(A); //Now we have ----> tmp -> B -> A
A.setNext(C); //Now we have ----> tmp -> B -> A -> C --->
node_A
は、最初のノードであることを起こるかnode_B
が最後のノードであることを起こるならば、お奨めは、あなたが心に留めておきたいかもしれませんそこにいくつかの追加の条件があるなら。
node_A
があなたのリンクリストの最初のノードであることを起こる場合は伝えることができ、あなたのようなチェックのためにいくつかを持つことができます。
public void swap (NodeStructure nodeStructure, Node Node_A, Node Node_B){
Node A = Node_A;
Node B = Node_b;
if(nodeStructure.head == A){
//Node A is the first Node, so we need to handle it in a special way.
Node tmp = Node_A;
nodeStructure.setHead(B); //Now we have -> B
B.setNext(tmp); //Now we have -> B -> A
A.setNext(C); //Now we have -> B -> A -> C ------>
}
//or in the case of the tail
if(nodeStructure.tail == B){
//Node B is the last Node, in this case, we don't need node_C
/*Iterate through nodeStructure until you reach node before A and
assign this to tmp.*/
nodeStructure.setTail(A); //Let's set the tail first
tmp.setNext(B); //Now we have ----> tmp -> B
B.setNext(A); //Now we have ----> tmp -> B -> A
}
/* Depeding on how you decide to implement, you might also have a third
condition checking if Node_A is the head and Node_B is tail.*/
//Handle condition where there's no special cases.
}
2つのノードを切り替えようとしていますか? – Samuel
私はcurrentとcurrent.nextを切り替えることを目指しています – user3105072
私は大学でこれをやりましたが、私が交換したい最初の 'node'の前に' node'をつかんでいました。この時点で、次の3つの 'nodes'を正しくリンクするだけです。 – robotlos