My Java solution with O(n)


  • 1
    M
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head==null||head.next==null) return head;
            ListNode temp=head;
            head=head.next;
            ListNode pre=null;//上一组的最后一个节点
            //两个为一组
            while(temp!=null&&temp.next!=null){
                ListNode a=temp.next;
                ListNode b=temp.next.next;
                if(pre!=null){
                   pre.next=a;
                }
                pre=temp;
                a.next=temp;
                temp.next=b;
                temp=b;
            }
            return head;
        }
    }

Log in to reply
 

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