I was trying to swap the adjacent nodes of a linked list using queues. Below is the code:
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;
}
}
I tried this but got an error that says: Found cycle in the ListNode. Please help. When I tried debugging, I found q2.offer(q1.poll());
seems to be causing the problem.
P.S. I know there is a simpler way to solve this question that is, a single iteration and using pointers. But I am a little new to programming . So I am trying out things but cannot figure out why the above code gives an error.