两两交换链表中的节点
题目
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例一:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
思路
正常模拟即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode* dummyhead = new ListNode(-1); dummyhead->next = head; ListNode* cur = dummyhead; while(cur->next != nullptr && cur->next->next!=nullptr){ ListNode* temp0 = cur->next; ListNode* temp1 = cur->next->next->next; cur->next = cur->next->next; cur->next->next = temp0; cur->next->next->next = temp1;
cur = cur->next->next; } ListNode* res = dummyhead->next; delete dummyhead; return res; } };
|