我已经尝试了一段时间来实现在单个链接列表中交换节点的指针而没有很多成功,所以任何帮助都是完全可以接受的(我已经阅读并尝试在我的代码中使用了很多以前的问题的答案,但似乎我做错了什么..)
以下是代码:
public void implementation() {
count = new long[5];
for (int i = 0; i <= 4; i++) {
count[i] = count2++;
}
Link[] nodeList2 = LinkList.Insert_Link(count,count.length);
for (int i = 0; i < nodeList2.length - 1; i++) {
nodeList2[i].next = nodeList2[i + 1];
}
for (int i = 0; i < nodeList2.length - 1; i += 2) {
LinkList.Swap_Node_Pointers(nodeList2[i], nodeList2[i + 1]);
}
// LinkList.Swap_Node_Pointers(nodeList2[1], nodeList2[1 + 1]);
LinkList.display(nodeList2);
}
Insert,Swap_Node_Points和display的代码是:
public Link[] Insert_Link(long[] value, int countlength) {
final Link[] nodeList = new Link[countlength] ;
for (int i = 0; i < nodeList.length; i++) {
nodeList[i] = new Link();
nodeList[i].value2 = value[i];
}
return nodeList;
}
public void display(Link[] b) {
Link[] nodeList2 = b;
for (int i = 0; i < nodeList2.length; i++) {
System.out.println("The value is" +nodeList2[i].value2);
System.out.println("");
}
}
public void Swap_Node_Values(final Link n1, final Link n2) {
long value;
// Link temp = null;
value = n1.value2;
n1.value2 = n2.value2;
n2.value2 = value;
}
public void Swap_Node_Pointers(Link n1, Link n2) {
Link temp = n1.next;
n1.next = n2.next;
n2.next = temp;
}
答案 0 :(得分:1)
链接列表中的节点交换(指针)没有任何意义。你应该交换(指针)值对象(就像你在代码中实际做的那样)。我将在编写实际实现之前先设计接口。
由于Java中单链表和双链表之间的性能差异很大,我会使用默认的LinkedList实现。也就是说,我写了你可以用来完成任务的接口/类:
public class ValueHolder<T> {
private T value;
public ValueHolder(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public void swap(ValueHolder<T> valueHolder) {
T temp = getValue();
setValue(valueHolder.getValue());
valueHolder.setValue(temp);
}
@Override
public String toString() {
return getValue() != null ? getValue().toString() : null;
}
}
public interface SinglyLinkedList<T> extends Iterable<T> {
public void add(T value);
}
public class SystemOutPrinter {
public <T> void print(Iterable<T> iterable) {
Iterator<T> it = iterable.iterator();
while (it.hasNext()) {
System.out.println("Value: " + it.next());
}
}
}
...
// ValueHolders contain the actual values
ValueHolder<MyObject> vh1 = new ObjectValueHolder<MyObject>(obj1);
ValueHolder<MyObject> vh2 = new ObjectValueHolder<MyObject>(obj2);
// Create list
SinglyLinkedList<ValueHolder<MyObject>> list = new DefaultSinglyLinkedList<ValueHolder<MyObject>>();
// Add valueHolders to list
list.add(vh1);
list.add(vh2);
// Print
new SystemOutPrinter().print(list);
// Swap
vh1.swap(vh2);
// Print
new SystemOutPrinter().print(list);