我通过在
Java中实现双链接列表来解决问题.特别是交换2个以下节点(在我的情况下,一个节点包含一个政治候选人).
假设以下DLL:
head – > 1 – > 2 – > 3 – > 4 – >尾部
public static void reverseTwoNode(Node N1, Node N2){
N1.setNextNode(N2.getNextNode());
N2.setPreviousNode(N1.getPreviousNode());
if (N1.getNextNode() != null)
N1.getNextNode().setPreviousNode(N1);
if (N2.getPreviousNode() != null)
N2.getPreviousNode().setNextNode(N2);
N2.setNextNode(N1);
N1.setPreviousNode(N2);
}
作为输出,我从头到尾没有正确的DLL,但从头到尾都很好:
List of candidate
head-->Jacques-->Joseph-->Francis-->Gilbert-->tail
Reverse
tail-->Gilbert-->Francis-->Joseph-->Jacques-->head
Reverse nodes : Francis , Joseph
List of candidate
head-->Jacques-->Joseph-->Gilbert-->tail
Reverse
tail-->Gilbert-->Joseph-->Francis-->Jacques-->head
我已经写了这个方法reverseTwoNode的几个版本.
我甚至试图在节点内交换数据而不是交换节点,我有同样的问题.
你能帮助我很好,我用这个简单的功能花了这么多时间,我看不出什么打扰……
先感谢您,
也许是显示方法的结果?
/* Display DLL from head to tail
* @see java.lang.Object#toString()
* @return str
*/
public String toString(){
String str = "List of candidate \n";
str += "head-->";
Node iterator = this.getHead();
while (iterator != null) {
str += iterator.getCandidate().getName();
str += "-->";
iterator = iterator.getNextNode();
}
return str + "tail";
}
/**
* Return string that display DLL from tail to head
* @return str
*/
public String reverseToString(){
String str = "Reverse\n";
str += "tail-->";
Node iterator = this.getTail();
while (iterator != null) {
str += iterator.getCandidate().getName();
str += "-->" ;
iterator = iterator.getPreviousNode();
}
return (str + "head");
}
解决方案
我的方法addNode是false,这是在尾部添加节点的正确方法:
public void addNode(Node C){
if(tail == null){
this.head = C;
this.tail = C;
}
else{
this.tail.setNextNode(C);
this.tail.getNextNode().setPreviousNode(this.tail);
this.tail = this.tail.getNextNode();
this.tail.setNextNode(null);
}
this.size ++;
}