//#24 Swap Nodes in Pairs
//4ms 99.72%
#include <iostream>
using namespace std;
/**
* 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)
{
if(head == NULL || head->next == NULL) return head;
//after this point, all in coming linked lists have a size of 2 or more
ListNode *tmp;
tmp = head;
head = head->next;
tmp->next = head->next;
head->next = tmp;
//finish the swap of first pair
ListNode *p;
p = head->next;
while(p->next != NULL && p->next->next != NULL)
//make sure that there is at least one more pair to swap
//if none or just one, just skip as nothing is to swap
{
tmp = p->next->next->next;
p->next->next->next = p->next;
p->next = p->next->next;
p->next->next->next = tmp;
p = p->next->next;
}
return head;
}
};
[Leetcode]#24 Swap Nodes in Pairs
最新推荐文章于 2021-01-12 15:06:15 发布