Question

Formatted question description: https://leetcode.ca/all/206.html

Easy

Description

Example:

Input: 1->2->3->4->5->NULL

Output: 5->4->3->2->1->NULL

A linked list can be reversed either iteratively or recursively. Could you implement both?

Solution

The recursive solution is to do the reverse operation for head.next, and set head.next.next = head and head.next = null.

The iterative solution uses two pointers, prev and curr. Initially, prev is null and curr points to head. Each step, let nextTemp be the next node of curr before reversing curr. Set curr.next = prev. After that, set both prev and curr to the next step (that is, prev = curr and curr = nextTemp). The loop ends when all nodes in the original list are reversed.

Java