Java recursive and iterative solutions, both cost 0ms


  • 4
    R

    Recursive:

    public ListNode swapPairs(ListNode head) {
    		if (head == null || head.next == null) 
    			return head;
    		ListNode p1 = head, p2 = head.next, p3 = p2.next;
    		p1.next = p3;
    		p2.next = p1;
    		
    		if (p3 != null) {
    			p1.next = swapPairs(p3);
    		}
    		
    		return p2;
    	}
    

    Iterative:

    public ListNode swapPairs(ListNode head) {
    		if (head == null || head.next == null)
    			return head;
    		ListNode curr = head;
    		ListNode next = head.next;
    		ListNode newHead = next;
    		
    		curr.next = next.next;
    		next.next = curr;
    		
    		if (curr.next == null)
    			return newHead;
    		
    		while (curr.next.next != null) {
    			ListNode prev = curr;
    			curr = curr.next;
    			next = curr.next;
    		
    			prev.next = next;
    			curr.next = next.next;
    			next.next = curr;
    			
    			if (curr.next == null || curr.next.next == null)
    				break;
    				
    		}
    		
    		return newHead;
    	}

Log in to reply
 

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