仅使用指针的Java交换方法

时间:2019-02-05 00:44:18

标签: 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的列表尝试交换索引值和下一个值。问题是我不能只做智能的“切换值”事情。我必须切换指针,但是您可能会看到它拒绝正确切换

我还没有找到一个人来处理两个相邻的值互换而无法使用值的组合

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

1 个答案:

答案 0 :(得分:1)

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

原理是使用current的父级。

对于第一个元素,您需要特殊的变量来保存列表的第一个元素-我称它为start。 要弄清以后的情况,您可以:

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

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

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;
}