首页 > 解决方案 > 仅使用指针的 Java 交换方法

问题描述

public void swap(int index)
{
    //If the index = 0, then swap 0 and 1, if 10 is given, swap 10 and 11.
    Node current = start;

    for(int i = 0; i < index; i++)
    {
        current = current.next;
    }

    // = 2
    Node temp = current;
    // = 3
    Node temp2 = current.next;

    System.out.println("Temp = " + temp.value + " | Refernces to: " + temp);
    System.out.println("Temp = " + temp2.value + " | Refernces to: " + temp2);
    System.out.println();

    System.out.println("Current is 3 and now we switching to 2 | Current: " + current.value);
    System.out.println();
    //2 then goes to 3
    current = temp2;
    System.out.println("Current must equal 3 | Current: " + current.value);
    System.out.println();
    //3 turns into 2
    System.out.println("Current must equal 2 | Current: " + current.value);
    System.out.println();

    current = temp;

    System.out.println("Now current is suppose to be 3: " + current.value);


    System.out.println();

    current = start;
    while(current != null)
    {
        System.out.println(current.value + " | " + current);
        current = current.next;
    }

}

这使用 1,2,3,4 的列表来尝试交换索引值和下一个值。问题是我不能只做智能“切换值”的事情。我必须切换指针,但您可能会看到它拒绝正确切换

我还没有找到任何人处理相邻交换 2 个值并且无法使用值的组合

更新:一些修复。它根据打印完美地切换节点。问题是我仍然无法保存打印输出 print 1,3,2,4

标签: java

解决方案


我假设“索引值”是当前值,“下一个值”是 current.next,

原理是使用current的parent。

对于第一个元素,您需要保存列表第一个元素的特殊变量——我称之为开始。为了澄清以后你有:

列表 -> item0-> item1 -> item2 -> ...

这里的第一个变量“list”是“head”或“anchor”。您存储第一个元素的变量是头(或“锚”),称为开始(如在 OP 中)。

public void swap(int index) {
    Node prev;
    Node next;
    Node current = start;
    //special treatment, as the head changes!
    if (0 == index) {
        //define
        next = current.next;
        //do the swap
        current.next = next.next;
        next.next = current;
        start = next;   // the head changes!
        return;
    }
    //stop one before the one you need to swap(index-1)
    for (int i = 0; i < index - 1; i++) {
        current = current.next;
        System.out.println("Value is: " + current.value);
    }
    //define
    prev = current;
    current = prev.next;
    next = current.next;
    // do the swap:
    prev.next = next;
    current.next = next.next;
    next.next = current;
}

推荐阅读