两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
- 链表中节点的数目在范围 [0, 100] 内
- 0 <= Node.val <= 100
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #include <iostream> #include <vector> using namespace std;
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 || !head->next) { return head; } ListNode *dummy = head; while (dummy->next != nullptr) { if (dummy == head) { head = dummy->next; dummy->next = head->next; head->next = dummy; } else { ListNode *node = dummy->next; if (!node->next) { return head; } dummy->next = node->next; node->next = node->next->next; dummy->next->next = node; dummy = node; } } return head; } };
int main() { ListNode *inputs = new ListNode(0); vector<int> input = {1, 2, 3, 4}; ListNode *temp = inputs; for (int i = 0; i < input.size(); ++i) { temp->next = new ListNode(input.at(i)); temp = temp->next; } inputs = inputs->next;
ListNode *results = Solution().swapPairs(inputs); while (results != nullptr) { std::cout << results->val << " "; results = results->next; } }
|