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;
}


 

相关文章:

  • 2022-12-23
  • 2021-06-27
  • 2022-12-23
  • 2021-12-03
  • 2022-01-13
  • 2021-11-09
  • 2021-11-11
  • 2021-07-30
猜你喜欢
  • 2021-06-29
  • 2021-08-24
  • 2021-07-19
  • 2021-10-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案