1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; } Queue<ListNode> queue = new LinkedList<>(); ListNode p = head; while (p.next != null) { queue.add(p.next); queue.add(p); if (p.next.next == null) { break; } else if (p.next.next.next == null) { queue.add(p.next.next); break; } else { p = p.next.next; } } ListNode ans = queue.poll(); p = ans; while (!queue.isEmpty()) { p.next = queue.poll(); p = p.next; if (queue.size() == 0) { p.next = null; } } return ans; } }
|