力扣24. 两两交换链表中的节点
一、题目
二、图解
解释: 这题目我们首先需要用到三个指针pre, cur, next 进行对两个节点进行交换。
首先先说一下简单的节点交换原理,如下图所示,cur是当前节点,next是下一个节点,我们要让 当前节点cur的下一个指针指向下下个指针,则让cur.next = next.next, 让next.next = cur,这样就产生了对换,还有一个步骤就是要让pre的next指向next,这里是头部,有两个重点,一是要修改head,head = cur,二是让pre是null,因此pre没有next。然后让pre=cur,cur=next,现在还要判断cur是否为null,因为cur是null的话说明以及没有节点要交换了,若cur不为null则让next=cur.next 再继续判定。整个循环是通过判定cur和next是否为null
三、源码
代码如下(示例):
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null){
return head;
}
ListNode pre = null;
ListNode cur = head;
ListNode next = head.next;
while(cur != null && next != null){
cur.next = next.next;
next.next = cur;
if(pre != null){
pre.next = next;
}else{
head = next;
}
pre = cur;
cur = pre.next;
if(cur != null){
next = cur.next;
}
}
return head;
}
}