head2用来标记返回的位置
head1是我做的一个无意义的虚拟头节点
cur用于存放当前交换节点的第一个
temp存放第二个
/**
* 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 head2 = new ListNode(-1,head);//0
ListNode cur = head;
ListNode temp;
ListNode head1 = head2;
while(head1.next!=null&&head1.next.next!=null)
{
cur = head1.next;
temp = cur.next;
head1.next = temp;
cur.next = temp.next;
temp.next = cur;
head1 = cur;
}
return head2.next;
}
}
这个就很简单啦,就是head1=cur这个很不好想,因为我交换后让head=head.next.next;说实话也可以,但是我一开始没发现它可以等于cur,还以为等于temp,其实交换了呀!
总之java写这个真的不难,C的话我估计很难咯