问题:给一个链表,每2个节点交换一次,比如,Given 1->2->3->4
, you should return the list as2->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==NULL || head->next==NULL) return head;
//head node
ListNode* new_head=head->next;
head->next=head->next->next;
new_head->next=head;
//process
ListNode* pre_node=head;
while(pre_node->next!=NULL && pre_node->next->next!=NULL){
ListNode* tem_node=pre_node->next->next;
pre_node->next->next=pre_node->next->next->next;
tem_node->next=pre_node->next;
pre_node->next=tem_node;
pre_node=pre_node->next->next;
}
//result
return new_head;
}
};