*LeetCode-Swap Nodes in Pairs

指针的判断真的超级容易出错,多想几个test case 1,12,123都想全

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if ( head == null || head.next == null )
            return head;
        ListNode dummy = new ListNode(0);
        ListNode pre = dummy;
        ListNode first = head;
        ListNode second = head.next;
        while ( second!= null ){ //这个判断条件错了好几次
            pre.next = second;
            first.next = second.next;
            second.next = first;
            pre = first;
            first = first.next;
            if ( first == null ) //这里要多判断一下
                break;
            second = first.next;
        }
        return dummy.next;
    }
}

几个月前用c++刷的时候

    ListNode *swapPairs(ListNode *head) {
        if ( head == NULL || head->next == NULL)
            return head;
        else {
            ListNode * tempP = head;
            ListNode * tempPNext;
            ListNode *ret=head->next;
            ListNode *last=new ListNode(0);
            while (tempP!= NULL && tempP->next!=NULL ){
                tempPNext = tempP->next;
                last->next=tempPNext;
                tempP->next = tempP->next->next;
                tempPNext->next = tempP;
                last=tempP;
                tempP = tempP->next;
            }
            return ret;
        }
    }

discuss里面的recursive 但是超级难想 而且空间是n

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if ((head == null)||(head.next == null))
            return head;
        ListNode n = head.next;
        head.next = swapPairs(head.next.next);
        n.next = head;
        return n;
    }
}



你可能感兴趣的:(*LeetCode-Swap Nodes in Pairs)