non-recursive solution with constant space


  • 0
    C
    /**
     * 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) {
            ListNode pre = new ListNode(-1);
            pre.next = head;
            ListNode preHelper = pre;
            ListNode p = head;
            while(p!=null && p.next!=null){
                ListNode next = p.next;
                preHelper.next = next;
                preHelper = p;
                p.next = next.next;
                p = next.next;
                next.next = preHelper;
            }
            return pre.next;
        }
        
        
    }
    

Log in to reply
 

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