链表的题,看到就有点脑袋大,指针来回折腾一会就蒙了,还是多做些吧!如此简单的一道题!
public class SwapNodesinPairs {
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
//第一个节点
ListNode first = head;
//第二个节点
ListNode second = head.next;
ListNode temp = head;
head = second;
while(first != null && second != null){
//为了保证链不断,第一次循环用不到,后面循环会用到
temp.next = second;
//交换
first.next = second.next;
second.next = first;
temp = first;
first = first.next;
if(first != null){
second = first.next;
}
}
return head;
}
}