提交代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null) return head;
int tmp;
ListNode p=head;
while(p!=null&&p.next!=null) {
tmp=p.val;
p.val=p.next.val;
p.next.val=tmp;
p=p.next.next;
}
return head;
}
}
运行结果: