给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:

输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
尾递归:比普通的递归好,具体自行搜索。
lic class seqecStack {
public ListNode reverseList(ListNode head) {
return reverse(head,null);
}
public ListNode reverse(ListNode head,ListNode tail)
{
if(head==null)
return tail;
ListNode next= head.next;
head.next=tail;
return reverse(next,head);
}
非尾递归
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null)
{
return head;
}
ListNode next=head.next;
ListNode newHead=reverseList(next);
next.next=head;
head.next=null;
return newHead;
}
这篇博客介绍了如何使用尾递归和非尾递归两种方法来反转单链表。提供了具体的Java代码实现,包括示例输入和输出。示例展示了从头节点为[1,2,3,4,5]的链表到[5,4,3,2,1]的反转过程。此外,还讨论了尾递归在性能上的优势。

被折叠的 条评论
为什么被折叠?



