0ms, single pass, O(n), O(1), iterative java solution.


  • 0
    A
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
     //Single pass, O(n), O(1) java solution.
     //Using three pointers: current, previous, next.
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head==null || head.next== null) return head;
            ListNode pre = null, cur= head, nex= head.next;
            
            while(cur!=null && cur.next!=null){
                nex=cur.next;
                cur.next= nex.next;
                nex.next = cur;
                if(pre==null) head = nex;
                else pre.next = nex;
                pre=cur;
                cur= cur.next;
            }
            return head;
        }
    }
    

Log in to reply
 

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