0
点赞
收藏
分享

微信扫一扫

Linux C++ 053-设计模式之模板方法模式

小编 2024-07-24 阅读 24

画图

注意有虚拟头结点

注意判断时先判断cur->next != nullptr,再判断cur->next->next != nullptr

注意末尾返回dumyhead->next,用新建result指针来接并返回

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *dummyhead = new ListNode(0);
        dummyhead->next =  head;
        ListNode *cur = dummyhead;
        while(cur->next != nullptr && cur->next->next !=nullptr)
        {
            ListNode *tmp = cur->next;
            ListNode *tmp1 = cur->next->next->next;
            cur->next = cur->next->next;
            cur->next->next = tmp;
            cur->next->next->next = tmp1;

            cur = cur->next->next;
        }
        ListNode *result = dummyhead->next;
        delete dummyhead;
        return result;


    }
};
举报

相关推荐

0 条评论