反转链表(含图解)
反转链表(含图解)
题目
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
图解
题解
ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tail = reverse(head.next);
head.next.next = head;
head.next = null;
return tail;
}
var reverse = function(head) {
if (head === null || head.next === null) {
return head;
}
var tail = reverse(head.next);
head.next.next = head;
head.next = null;
return tail;
}
def reverse(head: ListNode) -> ListNode:
if not head or not head.next:
return head
tail = reverse(head.next)
head.next.next = head
head.next = None
return tail
func reverse(head *ListNode) *ListNode {
if head == nil || head.next == nil {
return head
}
tail := reverse(head.next)
head.next.next = head
head.next = nil
return tail
}