##### Leetcode 206 Python Solution

Given the `head` of a singly linked list, reverse the list, and return the reversed list.

Example 1:

```Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
```

Example 2:

```Input: head = [1,2]
Output: [2,1]
```

Example 3:

```Input: head = []
Output: []
```

Constraints:

• The number of nodes in the list is the range `[0, 5000]`.
• `-5000 <= Node.val <= 5000`

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

### Solution:

#### Iterative:

```# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre = None
while curr:
nxt = curr.next
curr.next = pre
pre = curr
curr = nxt
return pre
```

#### Recursive:

```# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
return None

Uk01 on Feb 02, 2022 at 11:02 am

If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.

×