Simple Java solution with constant space (no recursion)


  • 0
    N
    public class Solution {
            public ListNode swapPairs(ListNode head) {
                ListNode pre = new ListNode(0);
                ListNode temp = new ListNode(0);
                ListNode r = new ListNode(0);
        
                int count = 0;
                while(head!=null){
                    if(head.next == null){
                        pre.next= head;
                        head = head.next;
                    }
                    else{
                        temp = head.next.next;
                        pre.next = head.next;
                        pre.next.next = head;
                        head.next = temp;
                        head = temp;
                    }
                    if(++count==1){
                        r = pre;
                    }
                    pre = pre.next.next;
                }
                
                return r.next;
            }
        }
    

  • 0
    N

    I used "pre" node to record the previous node, and link the revised node to it.


Log in to reply
 

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