如图1所示,本题不需要创建虚拟头节点:若创建虚拟头节点dummy,最后翻转得到结果,节点1的下一个节点为dummy。但是按照题意,节点1下一个节点应该为null
![在这里插入图片描述](https://img-blog.csdnimg.cn/2eb3556873df4d7bb841ae9fef448f1b.png)
如上图2所示,我们首先令pre=null,保存一下cur.next节点(即temp节点),因为当cur.next指pre时,我们便无法通过cur.next获取到temp节点(因此需提前保存)。
while(cur!=null){
temp = cur.next;
cur.next = pre;
pre = cur;//1
cur = next;//2
//代码片段1和2不可切换位置
}
完整代码如下:
*/ 递归法
class Solution {
public ListNode reverseList(ListNode head) {
return reverse(null, head);
}
public ListNode reverse(ListNode pre, ListNode cur){
if(cur == null) return pre;
ListNode next = cur.next;
cur.next = pre;
return reverse(cur, next);
}
}
/* 迭代法
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode next = null;
if (cur == null) return null;
while(cur!=null){
next = cur.next;
cur.next = pre;
pre = cur;//1
cur = next;//2
//代码片段1和2不可切换位置
}
return pre;
}
*/
完整代码:
/**
* 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 {
//1、若链表长度为奇数2n+1,只需对前2n个节点交换,最后1个节点不做处理。
public ListNode swapPairs(ListNode head) {
//2、本题中设置虚拟头节点,头结点与索引为index=2的节点区别:无前前面的节点指向头结点,但对于index=2节点,会存在index=1节点指向。
ListNode dummy = new ListNode(0);
dummy.next = head;//不可少。
ListNode prev = dummy;
while(prev.next!=null && prev.next.next!=null){
ListNode temp = head.next.next;
prev.next = head.next;
head.next.next = head;
head.next = temp;
prev = head; //而不是prev=temp
head = head.next;
}
return dummy.next;
}
}
参考文献:
[1] 代码随想录 - 两两交换链表中的节点