思路
定义一个指针cur, 先指向头节点,
1.判断后一个节点是否为空,不为空则交换值,
2.指针向后走两次
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode cur = head;
while (cur != null&&cur.next!=null) {
int temp=cur.val;
cur.val=cur.next.val;
cur.next.val=temp;
cur = cur.next;
cur = cur.next;
}
return head;
}
}