Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
贴个递归代码,一次Accept。
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode temp = head.next;
ListNode reverseHead = reverseList(head.next);
temp.next = head;
head.next = null;
return reverseHead;
}
哈哈,其实是我之前就研究过这个问题,有兴趣可以去看看,还有非递归的算法。
逆转链表问题链接