Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
题目大意:两两交换节点
/**
* 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* p,*q;
p=head;
if(p==NULL)
return head;
q=head->next;
if(q==NULL)
return head;
while(q!=NULL&&q->next!=NULL){
int temp=p->val;
p->val=q->val;
q->val=temp;
p=p->next->next;
q=q->next->next;
}
if(p!=NULL&&q!=NULL){
int temp=p->val;
p->val=q->val;
q->val=temp;
}
return head;
}
};
另:直接交换节点的值也是可以的
/**
* 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==NULL)
return head;
ListNode *p,*q;
p=head,q=head->next;
while(q!=NULL){
swap(p->val,q->val);
p=q->next;
if(p==NULL)
break;
q=p->next;
}
return head;
}
};