【问题标题】:Switch values in a linked list (dealing with nodes)在链表中切换值(处理节点)
【发布时间】:2014-03-06 04:11:21
【问题描述】:
我正在编写一个方法来切换链表中的一对值。
例如,我的列表包含:
1, 4, 5, 8, 9, 3
在方法调用之后,列表应该包含:
4, 1, 8, 5, 3, 9
仅使用节点来处理链表让我感到困惑,我不明白为什么我的代码只切换列表中的前 2 个值。有任何想法吗?多一点解释会很棒。谢谢。
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;
}
}
【问题讨论】:
标签:
java
linked-list
nodes
【解决方案1】:
将您的ListNode 变量名称更改为first 和second,这样会更容易发现问题。您没有正确交换,也没有正确迭代ListNodes。您必须将两者都迭代 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
}
}
【解决方案2】:
这是因为您没有更改正面值。前面一直在第一个和第二个数字之间变化。但是由于电流最初设置为前,每次电流值都会增加,直到达到最后一个值