/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//模拟题,直接按照题意交换相邻结点即可
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode newHead(-1);
newHead.next = head;
ListNode *pre = &newHead;
ListNode *cur = head;
while(cur != nullptr && cur->next != nullptr){
pre->next = cur->next;
pre = cur;
ListNode *tmp = cur->next;
cur->next = tmp->next;
tmp->next = cur;
cur = cur->next;
}
return newHead.next;
}
};
LeetCode之Swap Nodes in Pairs
最新推荐文章于 2024-10-10 01:02:39 发布