My solution-iterative-seems fast :)


  • 0
    T
    public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode pre = new ListNode(-1);
        pre.next = head;
        ListNode i = head, j = i.next;
        head = head.next;
        while(j!=null){
            i.next = j.next;
            j.next = i;
            pre.next = j;
            pre = i;
            i = i.next;
            j = (i != null) ? i.next:null;
        }
        return head;
    }
    

    }


Log in to reply
 

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