Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
代码如下:
/**
* 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) {
if(!head || head->next == nullptr)
return head;
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *pre = dummy;
ListNode *cur = head;
while(cur && cur->next) {
ListNode *temp = cur->next;
cur->next = temp->next;
temp->next = cur;
pre->next = temp;
pre = cur;
cur = cur->next;
}
return dummy->next;
}
};