java - 切换链表中的值(处理节点)

标签 java linked-list nodes

我正在编写一个方法来切换链接列表中的一对值。

例如,我的列表包含:

1, 4, 5, 8, 9, 3

方法调用后,列表应包含:

4, 1, 8, 5, 3, 9

仅使用节点来处理链表让我感到困惑,我不明白为什么我的代码只切换列表中的前两个值。有任何想法吗?多一点解释就太好了。谢谢。

public void switchPairs() {
    ListNode current = front;
    ListNode temp = front.next;
    while(current.next != null) {
        int i = front.data;
        front.data = front.next.data;
        front.next.data = i;

        current = current.next;
    }
}

最佳答案

ListNode 变量名称更改为 firstsecond,这样会更容易发现问题。您没有正确交换也没有正确迭代两个 ListNode。您必须将两者迭代 2。

public void switchPairs() {
    ListNode first = front;//first node in pair
    ListNode second = front.next;//second node in pair

    //while the both nodes are not null
    while(first != null && second != null) {
        int i = first.data;//put first value in temp value
        first.data = second.data;//put second value in first node
        second.data = i;//put temp value (first value) in second node

        //NOTE:  do some null pointer checks here just in case
        first = second.next;//iterate first node
        second = second.next.next;//iterate second node
    }
}

关于java - 切换链表中的值(处理节点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22214752/

相关文章:

java - 安卓蓝牙连接到配对设备

java - 如何使用 JDK 11 为 Collection.toArray() 提供生成器函数?

c - 在C中如何使链接列表中的最后一个元素指向null

javascript - TypeError : Argument 1 of Node. appendChild 没有实现接口(interface)Node

java - 内部类中的泛型类型

java - java中的问号是什么意思?

java - SPOJ 阶乘问题

java - 链表的冒泡排序实现

C++删除成员函数中的临时节点?

javascript - 检测 DOM 变化事件