我自己的代码:
class Solution {
public ListNode swapPairs(ListNode head) {
//两两交换
if(head == null){return head;}
else if(head.next == null){return head;}//两种特殊情况
else{
ListNode pre = head;//
ListNode cur = head.next;
ListNode temp = cur.next;
pre.next = temp;//注意这里的顺序,防止形成一个环!
cur.next = pre;
head = cur;//重新命名头节点
pre = temp;//定位到下一个
ListNode prepre = head.next;//还得记录pre节点前面那个节点
while(pre != null && pre.next != null ){//有待测试
cur = pre.next;
temp = cur.next;//临时节点标记
pre.next = temp;//
cur.next = pre;
prepre.next = cur;//完成交换
prepre = pre;//下一次定位
pre = temp;
}
return head;
}
}
}
思路分析:
1:对于头节点,需要单独处理
2:如何进行交换??????
//第一:防止形成一个环
pre.next = temp; 等同于 pre.next = cur.next;//先改变前面节点的指向,防止成环
cur.next = pre;//改变后面节点的指向(与反转数组有相似之处)
prepre.next = cur;//这一步同样也很重要,改变指向
//第二:交换完成,进行节点位置调整
//位置调整的时候尽量不要使用 .next 的方式!!!!!!!!!!!
prepre = pre;//不要忘了这个节点
pre = temp;
//下一步进行cur节点的调整时,可能会出现空指针异常(nullpointerException)
所以注意顺序,如何调整这里
这里直接返回判断
while(pre != null && pre.next != null)//这里不使用cur是因为cur还没有进行位置改变
//如果pre==null 或者 pre.next == null,循环结束
//如果都不为空,说明至少还有两个节点
cur = pre.next;
temp = cur.next;//可以进行位置调整,避免空指针异常
addition:
&& 短路运算符
前后一共记录了四个节点的位置