您的位置:首页 > 游戏 > 游戏 > 力扣 24两两交换链表中节点

力扣 24两两交换链表中节点

2024/10/6 22:22:34 来源:https://blog.csdn.net/weixin_43261508/article/details/140327786  浏览:    关键词:力扣 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;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com