Java solution


  • 0
    S
    public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode prev = new ListNode(-1);
            ListNode result = prev;
            ListNode next = null;
            while (head != null && head.next != null) {
                next = head.next;
                prev.next = next;
                head.next = next.next;
                next.next = head;
                prev = head;
                head = prev.next;
            }
            return result.next;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.