# In-place iterative and recursive Java solution

• ``````public ListNode reverseList(ListNode head) {
/* iterative solution */
ListNode newHead = null;
while (head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}

public ListNode reverseList(ListNode head) {
/* recursive solution */
return reverseListInt(head, null);
}

private ListNode reverseListInt(ListNode head, ListNode newHead) {
if (head == null)
return newHead;
ListNode next = head.next;
head.next = newHead;
return reverseListInt(next, head);
}``````

• This post is deleted!

• Thanks for sharing. But in your iterative solution, this line of code:
ListNode next = head.next;
essentially takes O(n) EXTRA space, right? So is this really an in-place solution? I don't think so. I mean if we're using O(n) EXTRA space, we can just simply store all values and construct a new linked list, no?

• Please note it's is tagged with "Java". You will not use extra memories unless you use `new ListNode()`. All java objects live in java Heap.

• ListNode next = head.next;

I suggest you not to use "next" when you produce a name of ListNode, cause the word "next" is really special, right?

• @Harrywithcode I don't think there is any ambiguity here.

• @Harrywithcode right

• @fanfeng_boston This takes constant space just for temporary value, so that it must be O(1), and in place

• @Harrywithcode vars of "pre, cur, next" are frequently used in LinkList solution

• when i run the iterative soultion, it shows that "Submission Result: Time Limit Exceeded".what's wrong with it?

• @LeeLom iterative solution is really O(1) space and O(n) time. I see no way to improve the complexity.

• This post is deleted!

• @cdai that is not a tail recursion

• @braydenCN Thanks for pointing out. Yes, that might be a problem causing stackoverflow.

• @braydenCN I was wondering why this is not a tail recursion?

• @Harrywithcode vars of "pre, cur, next" are frequently used in LinkList solution

Wondering why downvotes here and in previous posts. these are meaningful discussions.

• If you use the recursive version, that will already use linear stack space (every method call creates new stack entries).
With linear space it's simpler to just create new `ListNode`s as you iterate over the old one.

• @braydenCN Agree, it's more meaningful.

• How will this solution deal with loops in list?

• @marrow Normally lists should not have loops in them. It should be specially noted and handled.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.