【发布时间】:2020-08-01 19:14:40
【问题描述】:
我试图使用队列交换链表的相邻节点。下面是代码:
class Solution {
public ListNode swapPairs(ListNode head) {
Queue<ListNode> q1 = new LinkedList<>();
Queue<ListNode> q2 = new LinkedList<>();
ListNode curr = head;
while(curr != null && curr.next != null){
q1.offer(curr);
curr = curr.next.next;
}
curr = head.next;
while(curr != null || !q1.isEmpty()){
if(curr != null)
q2.offer(curr);
q2.offer(q1.poll()); //this line seems to be the problem
if(curr.next != null)
curr = curr.next.next;
else
curr = curr.next;
}
ListNode dummy = new ListNode(0);
curr = dummy;
while(!q2.isEmpty()){
dummy.next = q2.poll();
dummy = dummy.next;
}
return curr.next;
}
}
我尝试了这个,但收到一个错误消息:在 ListNode 中找到循环。请帮忙。当我尝试调试时,我发现q2.offer(q1.poll()); 似乎是导致问题的原因。
P.S. 我知道有一种更简单的方法可以解决这个问题,即单次迭代和使用指针。但我对编程有点陌生。所以我正在尝试一些东西,但无法弄清楚为什么上面的代码会出错。
【问题讨论】:
-
这个例子geeksforgeeks.org/…怎么样?检查
// If x is not head of linked list后的代码 -
在 Java 队列中,提供和轮询返回值,并且是添加和删除抛出异常的替代方法。您没有检查返回值。
-
知道了.. 感谢 Traycho Ivanov 和 NomadMaker!
标签: java data-structures linked-list queue swap