单链表反转--递归非递归实现
Java
接口: ListNode reverseList(ListNode head)
非递归的实现
有2种,参考
- 头结点插入法
- 就地反转
递归的实现
- Divide the list in two parts - first node and rest of the linked list.
- Call reverse for the rest of the linked list.
- Link rest to first.
- Fix head pointer
- Time Complexity: O(n)
- Space Complexity: O(1)
用Java
实现,第4步要稍微变通一下:用一个全局头结点dummy指针来保存新链表的head。 需要一个辅助的函数void reverseList(ListNode head)
(不带返回值的函数)
ListNode dummy = new ListNode(-1);
public ListNode reverseListRecu(ListNode head) {
if (head == null)
return head;
reverse(head);
return dummy.next;
}
private void reverse(ListNode head){
ListNode first = head;
ListNode rest = first.next;
if(rest == null) {
dummy.next = first;
return;
}
reverse(rest);
first.next.next = first;
first.next = null;
}