题目描述:
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:
Given 1->2->3->4, you should return the list as 2->1->4->3.
程序:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *p = NULL,*q = NULL,*r = NULL;
if(head && head->next){
p = head->next;
head->next = p->next;
p->next = head;
head = p;
p = head->next;
}
if(p)
q = p->next;
if(q)
r = p->next->next;
while(q && r){
p->next = r;
q->next = r->next;
r->next = q;
p = q;
q = p->next;
if(q) r = p->next->next;
else r = NULL;
}
return head;
}
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。