题目
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
数据范围
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
测试用例
示例1

java
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例2

java
输入:head = [1,2]
输出:[2,1]
示例3
java
输入:head = []
输出:[]
题解1(时间On空间O1)
java
/**
* 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) {
ListNode pre=null;
ListNode cur=head;
while(cur!=null){
ListNode next= cur.next ;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}
题解2(时空On)
java
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;
} }
`
## 思路
这道题感觉没必要讲啥思路了,最经典最基础数据结构链表翻转的两个方法,能理解就好,不能理解背就完了!!