My silly Java code with 85.84% (Iterative)


  • 0
    V
    public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null)
                return head;
            ListNode p = head;
            ListNode q = head.next;
            head = head.next;
            while (q.next != null && q.next.next != null) {
                q = q.next;
                p.next.next = p;
                p.next = q.next;
                p = q;
                q = q.next;
            }
            if (q.next == null) {
                p.next = null;
                q.next = p;
                return head;
            }
            if (q.next != null && q.next.next == null) {
                p.next = q.next;
                q.next = p;
            }
            return head;
    }
    

Log in to reply
 

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