# 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.

# Code

Java

• 

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/

/*
1,2,3,4,5
2,1 prev=2 - 3,4,5 current=3
3,2,1 prev=3 - 4,5 current=4
...
*/
class Solution_oj_iterative {
ListNode prev = null;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
}
class Solution_oj_recursively {
return p;
}
}

class Solution_recursively {

ListNode dummy = new ListNode(0);

reverse(dummy, current);

return dummy.next;
}

private void reverse(ListNode dummy, ListNode current) {

if (current == null) {
return;
}

ListNode oldDummyNext = dummy.next;

dummy.next = current;
current.next = oldDummyNext;

this.reverse(dummy, current);
}
}

class Solution_iteratively {

ListNode dummy = new ListNode(0);

while (current != null) {

ListNode oldDummyNext = dummy.next;

dummy.next = current;
current.next = oldDummyNext; // initial node, oldDummyNext is null, which is what we want, and which is why "// dummy.next = head;" is commented out above

}

return dummy.next;
}
}
}

• // OJ: https://leetcode.com/problems/reverse-linked-list/
// Time: O(N)
// Space: O(1)
class Solution {
public:
ListNode h;
p->next = h.next;
h.next = p;
}
return h.next;
}
};

• # Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
def reverseList(self, root):
if not root or not root.next:
return root

ret = self.reverseList(root.next)
root.next.next = root
root.next = None
return ret

pre = None
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre

# iteratively as queue head inserting
"""
:rtype: ListNode
"""
while p:
tmp = dummy.next
dummy.next = p
p = p.next
dummy.next.next = tmp

# easily leads to a circle. Remove current node's next after recursive call.

if p: