Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
思路:三指针 替换 即可
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode *newhead = new ListNode(0);
ListNode *pre = newhead;
pre->next = head;
ListNode *l1 = head;
ListNode *l2 = head->next;
while (l1&&l2){
l1->next = l2->next;
pre->next = l2;
l2->next = l1;
pre = l1;
l1 = l1->next;
if(l1)
l2 = l1->next;
}
return newhead->next;
delete newhead;
}
};