我正在编写一个方法来切换链接列表中的一对值。
例如,我的列表包含:
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
变量名称更改为 first
和 second
,这样会更容易发现问题。您没有正确交换也没有正确迭代两个 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/