Description
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.
解题思路
自己的方法:
/**
* 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==nullptr||head->next==nullptr)
return head;
ListNode* pHead=new ListNode(0);
pHead->next=head;
ListNode* pNode=pHead;
while(pNode->next!=nullptr&&pNode->next->next!=nullptr)
{
ListNode* temp=pNode->next;
pNode->next=pNode->next->next;
temp->next=pNode->next->next;
pNode->next->next=temp;
pNode=temp;
}
return pHead->next;
}
};
很妙的方法:使用指针的指针,就可以了!!!
/**
* 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 **pp = &head, *a, *b;
while ((a = *pp) && (b = a->next)) {
a->next = b->next;
b->next = a;
*pp = b;
pp = &(a->next);
}
return head;
}
};