刷题思路来源于 代码随想录
/**
* 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){
return null;
}
ListNode slow=null;
ListNode fast=head;
while(fast!=null){
ListNode temp=fast.next;
fast.next=slow;
slow=fast;
fast=temp;
}
return slow;
}
}
/**
* 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){
return null;
}
return reverse(null,head);
}
public ListNode reverse(ListNode slow,ListNode fast){
if(fast==null){
return slow;
}
ListNode temp=fast.next;
fast.next=slow;
return reverse(fast,temp);
}
}