1. 程式人生 > >leetcode 24:兩兩交換連結串列中的節點

leetcode 24:兩兩交換連結串列中的節點

遞迴即可

ListNode* swapPairs(ListNode* head) {
    if(head==NULL)
        return NULL;
    ListNode* l1=head;
    ListNode *l2=new ListNode(0);
    if(l1!=NULL) {
        l2 = head->next;
        if (l2 == NULL)
            return head;
        l1->next = l2->next;
        l2->next = l1;
        if (head->next == NULL)
            return l2;
        l1->next = swapPairs(head->next);
    }
    return l2;
}