I'm working on a question which is asking to reverse a linked list:
Example:
For linked list 1->2->3, the reversed linked list is 3->2->1
Here is my code:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: You should return the head of the reversed linked list.
Reverse it in-place.
"""
def reverse(self, head):
# write your code here
prev = None
current = head
next = current.next
while(current is not None):
current.next = prev
prev = current
current = next
next = next.next
head = prev
return prev
After submit I got error. Could anyone help me to point out why it is wrong? The error message is saying that "next = current.next AttributeError: 'NoneType' object has no attribute 'next'". I tried to use next refer to the node next to the current node.
Thanks!