Share my iterative java solution


  • 1
    M
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if (head==null || head.next==null) { return head; }
            ListNode dummy = new ListNode(0); dummy.next = head;
            for (ListNode p=dummy; p.next!=null&&p.next.next!=null; p=p.next.next) {
                ListNode save = p.next.next.next;
                p.next.next.next = p.next;
                p.next = p.next.next;
                p.next.next.next = save;
            }
            return dummy.next;
        }
    }

Log in to reply
 

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