leetcode-24-两两交换链表中的节点

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == NULL || head->next == NULL ) return head;
        ListNode* dumhead = new ListNode(0);
        dumhead->next = head;
        ListNode* pre = dumhead;
        ListNode* curNode = head;
        while (curNode->next) {
            ListNode* next = curNode->next;
            curNode->next = next->next;
            next->next = curNode;
            pre->next = next;
            pre = curNode;
            if (curNode->next) curNode = curNode->next;
        }
        head = dumhead->next;
        delete dumhead;
        return head;
    }
};

int main()
{
    Solution sol;
    vector<int> input1 = {1,2,3,4,5,6};
    ListNode *head = createListNode(input1);
    printLinkedList(sol.swapPairs(head));
    deleteLinkedList(head);
    return 0;
}


 

相关文章: