Created
July 18, 2022 08:47
-
-
Save icameling/2ba9620dfaaf6c1858f31984df5c1eab to your computer and use it in GitHub Desktop.
#链表 #两两交换链表中的节点
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
ListNode* dummy = new ListNode(0); | |
dummy->next = head; | |
ListNode* cur = dummy; | |
while (cur->next != NULL && cur->next->next != NULL) { | |
ListNode* node1 = cur->next; // 1 | |
ListNode* node2 = cur->next->next; // 2 | |
ListNode* node3 = cur->next->next->next; // 3 | |
cur->next = node2; | |
cur->next->next = node1; | |
cur->next->next->next = node3; | |
cur = node1; | |
} | |
return dummy->next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment