交换链表中相邻的两个节点
1.注意交换之后,要将记录的上一个节点指向新的下一个节点,串成链表
/**
* 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 *ptr = head, *temp, *prev = NULL;
while(ptr && ptr -> next){
if(!prev){
head = ptr -> next;
}else{
prev -> next = ptr -> next;
}
temp = ptr -> next -> next;
ptr -> next -> next = ptr;
ptr -> next = temp;
prev = ptr;
ptr = temp;
}
return head;
}
};