My accepted Java solution without recursion


  • 0
    X
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head == null || head.next == null) return head;
            ListNode curr = head, pre = head;
            ListNode nex = head.next, newHead = head.next;
            while(curr != null){
                if(curr.next == null) break;
                nex = curr.next;
                pre = curr;
                if(nex.next == null){
                    nex.next = curr;
                    curr.next = null;
                    break;
                } 
                if(nex.next.next == null){
                    curr.next = nex.next;
                    nex.next = pre;
                    break;
                } 
                curr.next = nex.next.next;
                curr = nex.next;
                nex.next = pre;
            }
            return newHead;
        }
    }
    

Log in to reply
 

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