在单链表中交换相邻节点的值
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode res=new ListNode(0);
res.next=head;
while(head!=null && head.next !=null){
int temp=head.val;
head.val=head.next.val;
head.next.val=temp;
head=head.next.next;
}
return res.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* res=head;
while(head && head->next){
int temp = head->val;
head->val = head->next->val;
head->next->val=temp;
head=head->next->next;
}
return res;
}
};