leetcode 链接:两两交换链表中的节点
题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:![[中等] 24. 两两交换链表中的节点 - 图1](/uploads/projects/xf015y@ivbwyo/93c725c66bdc1510fc21b8b7c66ef8b5.jpeg)
输入:head = [1,2,3,4]输出:[2,1,4,3]
输入:head = []输出:[]
输入:head = [1]输出:[1]
解答 & 代码
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/class Solution {public:ListNode* swapPairs(ListNode* head) {if(head == nullptr || head->next == nullptr)return head;ListNode* dummyHead = new ListNode(-1, head);ListNode* pre = dummyHead;ListNode* cur = head;while(cur != nullptr && cur->next != nullptr){// 交换 cur 和其下一个节点ListNode* next = cur->next;cur->next = next->next;pre->next = next;next->next = cur;// 更新 pre 和 cur,以访问下一组节点进行交换pre = cur;cur = cur->next;}return dummyHead->next;}};
执行结果:
执行结果:通过执行用时:8 ms, 在所有 C++ 提交中击败了 53.84% 的用户内存消耗:7.4 MB, 在所有 C++ 提交中击败了 11.56% 的用户
