# LeetCode – Reverse Linked List (Java)

Java Solution 1 – Iterative

```public ListNode reverseList(ListNode head) { if(head==null||head.next==null) return head;   ListNode p1 = head; ListNode p2 = p1.next;   head.next = null; while(p1!=null&& p2!=null){ ListNode t = p2.next; p2.next = p1; p1 = p2; p2 = t; }   return p1; }```

Java Solution 2 – Recursive

```public ListNode reverseList(ListNode head) { if(head==null || head.next == null) return head;   //get second node ListNode second = head.next; //set first's next to be null head.next = null;   ListNode rest = reverseList(second); second.next = head;   return rest; }```

### 14 thoughts on “LeetCode – Reverse Linked List (Java)”

1. Solved in a much cleaner solution. See also execution example below.

Code:
``` Node reverse(Node n) { Node first = null;```

``` while(n != null) { Note next = n.next; n.next = first; first = n; n = next; } ```

``` return first; } ```

Execution example:
``` Input: 1->2->3->4```

``` n 1 2 3 4 null next 2 3 4 null first 1 2 3 4 ```

```Output: 4->3->2->1->null ```

2. A simpler recursive solution to this can be like below

reverseList(ListNode node, ListNode prevNode) {
if (node == null) {
return prevNode;
}
Node prevNextNode = node.next;
node.next = prevNode;

return reverseList(prevNextNode, node);
}

3. just check for p2

4. Yes, kushi, you’re right!
Its the corner condition.

5. +1

6. while(p1!=null&& p2!=null){
why not

while(p2!=null){

7. No, its not the same when you reach the end of the list. At the end of list p1 points to the last element and p2 points to null, when || is used the condition becomes true and you get NPE when p2.next is executed

8. Hi Lin,
you are right!

9. it calls again and again right..when next line second.next execute??

10. here we are calling reverseList(second)..So,when next line execute??

11. ` `

``` String foo = "bar"; ```

12. A more concise version. Is there a reason why use second, and keep it before recursion. This will work, too.