Reverse Linked List 递归非递归实现

单链表反转--递归非递归实现
Java接口: ListNode reverseList(ListNode head)

非递归的实现

有2种,参考

  • 头结点插入法
  • 就地反转

递归的实现

1) Divide the list in two parts - first node and rest of the linked list.
2) Call reverse for the rest of the linked list.
3) Link rest to first.
4) 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;
	}

你可能感兴趣的:(list)