Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
代码语言:javascript复制 public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode tail = head.next;
ListNode reversed = reverseList(head.next);
// 前后翻转tail和head
tail.next = head;
head.next = null;
return reversed;
}