https://leetcode.com/problems/reverse-linked-list/
206. Reverse Linked List
- Total Accepted: 149090
- Total Submissions: 353930
- Difficulty: Easy
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Code (Iterative)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
next_node = head.next
head.next = None
while next_node is not None:
next_next_node = next_node.next
next_node.next = head
head = next_node
next_node = next_next_node
return head
Code (Recursive)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
next_node = head.next
new_head = self.reverseList(next_node)
head.next = None
next_node.next = head
return new_head