0ms Solution!! Java


  • -1
    A
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null){
                return head;
            }
            
            ListNode current = head;
            ListNode next = head.next;
            ListNode prev = null;
            head = head.next;
            
            while (current != null && next != null){
                ListNode temp = next.next;
                current.next = temp;
                next.next = current;
                if (next != head){
                    prev.next = next;
                }
                prev = current;
                current = temp;
                if (current != null){
                    next = current.next;
                }
            }
            return head;
        }
    }

Log in to reply
 

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