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.
Subscribe to see which companies asked this question
/**
* 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* buffer=new ListNode(0);
buffer->next=head;
ListNode* prev=buffer;
while(head&&head->next)
{
prev->next=head->next;
head->next=head->next->next;
prev->next->next=head;
prev=prev->next->next;
head=head->next;
}
return buffer->next;
}
};
二刷时,解法更简单,而且更清晰。
思路就是,要用三个指针,head,l1,l2,分别指向要调换的两个节点的前面那个节点和要调换的两个节点。所以这就是为什么刚开始要让head指向newhead那个节点的原因(让他初始化为要调换的两个节点的前头)。
/**
* 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) return head;
ListNode* newhead=new ListNode(0);
newhead->next=head;
ListNode* l1=head;
ListNode* l2=head->next;
head=newhead;
while(l2&&l1)
{
head->next=l2;
l1->next=l2->next;
l2->next=l1;
head=l1;
l1=l1->next;
if(l1) l2=l1->next;
}
return newhead->next;
}
};