1.0版本思路(双指针)
常规解法了,俩指针,头指针pre,当前指针curr在head位置
废话不说了,都在注解里~
/**
* 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 reverseList(ListNode head) {
if(head==null||head.next==null){//节点为空或者只有一个的情况
return head;
}
//定义双指针
ListNode curr=head;
ListNode pre=null;
while(curr!=null){//注意,这里不是curr.next!=null,因为我们最后返回pre,所以curr指针就不用next来判断了
//临时保存一下temp节点的下一个
ListNode temp=curr.next;
//翻转链表
curr.next=pre;
//双指针往下走
pre=curr;
curr=temp;
}
return pre;
}
}
2.0版本思路(迭代)
迭代挺不好理解的,扒个评论区的解释吧
假设链表是[1, 2, 3, 4, 5]从最底层最后一个reverseList(5)来看
返回了5这个节点
reverseList(4)中
p为5
head.next.next = head 相当于 5 -> 4
现在节点情况为 4 -> 5 -> 4
head.next = null,切断4 -> 5 这一条,现在只有 5 -> 4
返回(return)p为5,5 -> 4
返回上一层reverseList(3)
处理完后返回的是4 -> 3
依次向上
递归版本
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}